[Django]-Reverse lookup on Django m2m field?

5👍

Django automatically creates a reverse relationship for you in this case, so with an instance of the Child model, you can find all Family instances to which the child belongs:

c = Child.objects.get(id=1)
c.family_set.all()  # gives you a list of Families

Since it’s unlikely a child will belong to multiple families, though, this isn’t really a Many-to-Many situation. You may wish to consider modelling the relationship on a child object:

class Family(models.Model):
    pass # your fields here

class Child(models.Model):
    family = models.ForeignKey(Family)

This way, you can get the family for a child using mychild.family, and get all the children in a family using django’s automatic reverse relationship myfamily.child_set.all().

3👍

See http://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships

The syntax is child.family_set.all() but can be changed with the related_name parameter.

Leave a comment