Monday, December 29, 2008

Model with Many to Many Child, Parent relationships

I wanted to create a model that had both multiple parents and multiple children symmetrically. That is setting the model as having a child would automatically set that child has having the current Model as one of it's parents.

class Person (models.Model):
children = models.ManyToManyField ("self",
symmetrical=False,
blank=True,
related_name="parent")

This allows us to set a child in the admin panel and that child then has the current model as the parent.

There is a down side to this method. That is that in the admin panel, you can only set children not parents.

I will fix this on the front-end interface manually, by adding a parent multi-select field that when saved will set them directly as parents.

Special thanks to Magus from the #django chat room.