使用带注释的查询集上的 Q 对象进行过滤
模拟测试用例:
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)
输出:
a_count: 1, b_count: 0
a_count: 0, b_count: 0
...
FAIL: testCount
self.assertEquals(qs2.count(), 1)
AssertionError: 0 != 1
为什么 |操作员改变了这样的行为,我该如何修复它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 v1.2.4 开始,这似乎仍然是一个未解决的问题。
我想您已经测试了错误报告中提供的补丁之一或诉诸原始查询,直到正式修复。
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.