Given the following model with two many-to-many relations:
class Child(models.Model):
name = models.CharField(max_length=80)
class Foo(models.Model):
bar = models.ManyToManyField(Child)
baz = models.ManyToManyField(Child)
This gives the error:
accounts.foo: Accessor for m2m field 'bar' clashes with related m2m field 'Child.foo_set'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Accessor for m2m field 'baz' clashes with related m2m field 'Child.foo_set'. Add a related_name argument to the definition for 'baz'.
Fine; I don’t need the backwards relation. According to the Django docs for related_name (which is only under ForeignKey as far as I can see), I can set related_name="+" and backward relations won’t be created:
class Child(models.Model):
name = models.CharField(max_length=80)
class Foo(models.Model):
bar = models.ManyToManyField(Child, related_name="+")
baz = models.ManyToManyField(Child, related_name="+")
This doesn’t work though:
accounts.foo: Accessor for m2m field 'bar' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Reverse query name for m2m field 'bar' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Accessor for m2m field 'baz' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'baz'.
accounts.foo: Reverse query name for m2m field 'baz' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'baz'.
What do I need to do to avoid creating reverse relations?
I think you need to just give the two fields different related_names:
If you don’t give a related name, then it’s trying to create the same accessor name (
foo_set) twice on theChildmodel. 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 aChildinstancec, you can access relatedFooobjects withc.bar.all()andc.baz.all().If you don’t want the backwards relations, then append a
+to each of the (unique) related names: