Django Many to Many circular reference?
django, python
Solution
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
Problem
conceptually what I want is this: ``` class Child: guardians = models.ManyToManyField(Guardian) class Guardian: children = models.ManyToManyField(Child) ``` The application is for a school. Any one parent(guardian) can have multiple children and any child can have multiple guardians. Now, I can't forward declare in python as I would in C++. What is the cleanest and best way to do this? Do I need a third 'Relationship' class to represent these connections (this is what I'm tending towards)? But before I reinvent the wheel I wanted to ask. It seems like this should be easy...