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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With