synic
synic

Reputation: 26668

Filtering a model by checking for presence in another model via ManyToMany relationship

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?

Upvotes: 1

Views: 118

Answers (1)

KillianDS
KillianDS

Reputation: 17176

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)

Upvotes: 5

Related Questions