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...
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With