Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse lookup on Django m2m field?

Tags:

python

django

I have a Django object called "Family". "Family" has the variable "children", which is a many to many field of a class called "Child".

If I have a "Child" object, is there a way I get the family object to which the child belongs?

Child
      some more fields...
Family
      children = models.ManyToManyField(Child)
      some more fields...
like image 696
Andrew Avatar asked Sep 03 '25 16:09

Andrew


1 Answers

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().

like image 109
Jarret Hardie Avatar answered Sep 05 '25 06:09

Jarret Hardie