Reputation: 177
my (simplified) models are like this:
class Story(models.Model):
wikiedit = models.BooleanField(default=False)
writers = models.ManyToManyField(User,null=True,blank=True)
class Writer(models.Model):
user = models.OneToOneField(User)
Now I am trying to build a queryset which includes all stories that meet: wikiedit = True or user in writers
So inside my view I make two queries:
wikistories = Story.objects.filter(wikiedit=True)
writerstories = request.user.objects.story_set.filter
But I would like to make this with just one database hit if it is possible. I guess it would be more efficient. I cannot find if the in operator is supported in this m2m relations in the sense:
Story.objects.filter(writers__contains=request.user) #but this is a TypeError
Maybe is just more efficient to make 2 querysets and then join them in a list, but would love to have it in one.
Any clues? Thx!
Upvotes: 1
Views: 118
Reputation: 599610
To check an M2M relation, you just do =
, not contains
:
Story.objects.filter(writers=request.user)
And you can use Q
objects to do an or
query:
Story.objects.filter(Q(wikiedit=True) | Q(writers=request.user))
Upvotes: 2