开发者

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'Publis开发者_运维知识库hed',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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜