Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django multiple many to many fields with same relationship on model

Can the same many to many relationship exist on a model multiple times (with different field names for the field)? I can't seem to get this to work when doing the migration as python complains about the relationship already existing when I try to duplicate it to a different name.

My model currently looks like this:

class UserLocations(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    locations = models.ManyToManyField(Locations, related_name="users")

I want to add an additional field called emails that is the same as the locations field. So would I just give it a different related name?

like image 495
Jasonca1 Avatar asked Mar 26 '19 17:03

Jasonca1


People also ask

How do you implement many-to-many relationships in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.


1 Answers

Yes you can have multiple manytomany relations with the same model. You have to have different related_name for both for reverse access. Like this

class MyModel(models.Model):
    relation_a = models.ManyToManyField(AnotherModel, related_name='rev_relation_a')
    relation_b = models.ManyToManyField(AnotherModel, related_name='rev_relation_b')

That's why django is complaining because you have to define explicitly separate related names for both.

like image 55
Nafees Anwar Avatar answered Oct 19 '22 10:10

Nafees Anwar