48👍
I think you need to just give the two fields different related_names:
class Child(models.Model):
name = models.CharField(max_length=80)
class Foo(models.Model):
bar = models.ManyToManyField(Child, related_name="bar")
baz = models.ManyToManyField(Child, related_name="baz")
If you don’t give a related name, then it’s trying to create the same accessor name (foo_set
) twice on the Child
model. If you give the same related name, it’s again going to try to create the same accessor twice, so you need to give unique related names. With the above code to define your models, then given a Child
instance c
, you can access related Foo
objects with c.bar.all()
and c.baz.all()
.
If you don’t want the backwards relations, then append a +
to each of the (unique) related names:
class Foo(models.Model):
bar = models.ManyToManyField(Child, related_name="bar+")
baz = models.ManyToManyField(Child, related_name="baz+")
20👍
You haven’t read Django’s documentation carefully enough. Here it says:
If you have more than one ManyToManyField pointing to the same model and want to suppress the backwards relations, set each related_name to a unique value ending with ‘+’.
The related_name
attributes have to be unique, not the same.
- [Django]-Error: could not determine PostgreSQL version from '10.3' – Django on Heroku
- [Django]-Django query datetime for objects older than 5 hours
- [Django]-Django Rest Framework – APIView Pagination