user290043
user290043

Reputation:

Django: 2 QuerySets and Duplicates

I have two QuerySets both containing the instances of the same model class.

class DBV:
    name = CharField
    description = TextField
    review_state = CharField(choices=[u"Draft",u"Published",u"Archived"])
    team_members = FK(User)
    deleted = Boolean

This is how I am filtering to get the two QuerySets:

res = DBV.objects.filter(deleted=False).filter(team_members=user)
if user.has_perm('dbv.can_view_dbv'):
    r = DBV.objects.filter(deleted=False).filter(review_state__in=[u'Published',u'Archived',])
    res = res + r

The first problem, of course, is that when you try to add QuerySets you get:

unsupported operand type(s) for +: 'QuerySet' and 'QuerySet'

So, what is the best way to merge these QuerySets and remove duplicates? I figure that there is isn't really a way to do that in Django besides writing the sql. Or?

Thank you! :) Eric

Upvotes: 2

Views: 2334

Answers (2)

Aleister
Aleister

Reputation: 153

You can use the | operator. ie

Queryset1 | Queryset2 this make the equivalent of union in sets. Queryset1 & Queryset2 will give you the intersection of the sets

Upvotes: 0

Adam Vandenberg
Adam Vandenberg

Reputation: 20651

You can convert the queries to lists and add the lists, if you need both sets of results, or you can use "Q" objects and or them together to combine query logic: http://docs.djangoproject.com/en/1.2/topics/db/queries/#complex-lookups-with-q-objects

Upvotes: 2

Related Questions