Marcio Cruz
Marcio Cruz

Reputation: 2069

How to query for an exact ManyToMany relation?

Let's say I have the following classes:

class Votable(models.Model):
    name = ...

class Vote(models.Model):
    options = models.ManyToManyField(Votable, related_name='+')
    choosen = models.ForeignKey(Votable)

Notes:

Vote.options have exactly 2 items

Vote.choosen is one of the 2 items of options

How do I make a query that search for the exact 2 items of Vote.options and also Vote.choosen?

I tried Vote.objects.get(options=[1,2], choosen=1) but it returns:

TypeError: int() argument must be a string or a number, not 'list'

Upvotes: 2

Views: 705

Answers (1)

You have to chain filters to get only vote objects that have both options 1 and 2.

Vote.objects.filter(options=1).filter(options=2).get(choosen=1)

If you wanted vote objects that had either options 1 OR 2 you'd use __in syntax:

Vote.objects.get(options__in=[1, 2], choosen=1)

Upvotes: 3

Related Questions