Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

django - Filtering with a Q object on an annotated QuerySet

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...