views:

231

answers:

2

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.

+5  A: 

It should be:

toy_instance.boy_set.all()

See here:

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

Gabriel Ross
+3  A: 
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