tags:

views:

27

answers:

1

Given the following two models:

class Card(models.Model):
    disabled = models.BooleanField(default=False)

class User(models.Model):
    owned_cards = models.ManyToManyField(Card)

Given a certain user, how can I, in one query, get all the Card objects that are not disabled, and are also present in that user's owned_cards field?

+4  A: 

It's actually quite simple, you can use the owned_cards field of a user object as a manager.

enabled_cards = theuser.owned_cards.filter(disabled=False)

Answer for the second question in the comments, this should work, using Q objects to negate the lookup.

not_owned_cards = Card.objects.filter(~Q(id__in=theuser.owned_cards.all()), disabled=False)
KillianDS
Crap, ok, what if you want to get all the cards that are NOT present in the owned_cards field?
synic