[Django]-Django Many to Many circular reference?

6👍

I am not sure if I understand the problem.

By doing this:

class Child:
    guardians = models.ManyToManyField('Guardian', related_name='children')

class Guardian:
    .... some other fields
    # children = models.ManyToManyField(Child)  <--- not needed

Is like saying “a child can have many guardians and a guardian can have many children”. You
don’t have to declare it in both models.

Also a third(intermediate) table is created anyway by django, behind the scenes. Because
this is how you model ManyToMany relationships in an RDBMS.

The only reason you’d want to explicitly create an intermediate model, is when you
have to put extra information that describes the specific many2many relationship.
i.e.

class Child:
    guardians = models.ManyToManyField('Guardian', 
        through='ChildGuardianMembership', related_name='children')

class Guardian:
    .... some other fields

class ChildGuardianMembership:
    child = models.ForeignKey(Child)
    guardian = models.ForeignKey(Guardian)
    created_at = models.DateTimeField(auto_now_add=True) # When was this relationship established?

In that case you have to be aware that since you declared an explicit intermediate model,
that this is the model to use when creating a relationship between a guardian and a child.

e.g.

ChildGuardianMembership.objects.create(child=child_inst, guardian=guardian_inst)

Adding extra fields on many2many relationships(as above) is described here

0👍

Relations are already bidirectional unless this is explicitly disabled.

Leave a comment