Reputation: 239810
I have Boys and Toys. Two django models. Toys can be owned by more than one Boy and each boy can own more than one Toy... So I've put a ManyToMany field in Boy.
If I want a list of toys owned by a single boy, it's easy. So good so far.
But now I need to get a list of Boys based on a Toy instance. The relationship should be symmetrical but I don't know the syntax.
Note: No, these aren't my real entity names - I just thought it might be easier to follow.
Upvotes: 2
Views: 374
Reputation: 31
from django.db import models
class Toy(models.Model):
name = models.CharField('Name', max_length=250)
def __unicode__(self):
return self.name
class Boy(models.Model):
name = models.CharField('Name', max_length=250)
toys_owned = models.ManyToManyField(Toy, blank = True)
def __unicode__(self):
return self.name
if toy = is instance of Toy class, then toy.boy_set.all() is what you looking for
Upvotes: 3
Reputation: 5198
It should be:
toy_instance.boy_set.all()
See here:
http://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships
Upvotes: 6