Filtering with a Q object on an annotated QuerySet

混江龙づ霸主 提交于 2019-12-18 06:48:55

问题


A mock testcase:

def testCount(self):
    qs = Test.objects.all()
    qs = qs.annotate(a_count=Count('a_items'), b_count=Count('b_items'))
    for item in qs:
        print 'a_count: %d, b_count: %d' % (item.a_count, item.b_count)
    qs1 = qs.filter(Q(a_count__gt=0))
    self.assertEquals(qs1.count(), 1)
    qs2 = qs.filter(Q(a_count__gt=0) | Q(b_count__gt=0))
    self.assertEquals(qs2.count(), 1)

Output:

a_count: 1, b_count: 0
a_count: 0, b_count: 0
...
FAIL: testCount 
    self.assertEquals(qs2.count(), 1)
AssertionError: 0 != 1

Why does the | operator change the behavior like this and how do I fix it?


回答1:


Looks like this is still an open issue as of v1.2.4.

I guess you'd have test one of the supplied patches in the bug report or resort to raw queries until it is officially fixed.



来源:https://stackoverflow.com/questions/4536535/filtering-with-a-q-object-on-an-annotated-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!