Reputation: 1853
I have the following class in my models.py
class Story(models.Model):
title = models.CharField(max_length=60)
creator = models.ManyToManyField(User, blank=True)
I am trying to return a QuerySet using 2 creator names.
For example, how would I filter for stories that have creators: User 1 obj and User 2 obj?
I have read the Many-to-Many relationships docs and could not find anything. The closest solution I have reached was...
Story.objects.filter(creator__in=[1,2]).distinct()
but it doesn't do a joint query for both 1 AND 2, just 1 OR 2.
Any help would be greatly appreciated!
Upvotes: 0
Views: 503
Reputation: 1595
You're going to need to us a Q object. I'd try something like this:
from django.db.models import Q
Story.objects.filter(Q(creator=1) | Q(creator=2))
Upvotes: 1
Reputation: 161
You can use Q objects for this:
https://docs.djangoproject.com/en/1.4/topics/db/queries/#complex-lookups-with-q-objects
Something like the following should do what you want:
Story.objects.filter(Q(creator=1), Q(creator=2))
Upvotes: 0