为什么在使用|(并集)的peewee查询中.count()返回错误的数量?
下面的前三个查询返回了正确的数字,而最后一个查询返回了错误的数字。它应该返回153,但实际上返回了8193。我完全不知道这个数字是从哪里来的。
通过遍历查询,确实可以正确返回153条记录。
>>> Project.select().where(Project.number.between('2012-01', '2012-02')).count()
75
>>> Project.select().where(Project.number.between('2012-02', '2012-03')).count()
78
>>> Project.select().where(Project.number.between('2012-01', '2012-03')).count()
153
>>> (Project.select().where(Project.number.between('2012-01', '2012-02')) |
Project.select().where(Project.number.between('2012-01', '2012-03'))).count()
8193
编辑
这里有一个函数,从一个空数据库开始,重现了这个问题。
def test(self):
db = peewee.SqliteDatabase('test.db', check_same_thread=False)
class Test(peewee.Model):
num = peewee.IntegerField()
class Meta:
database = db
Test.drop_table(True)
Test.create_table(True)
for i in range(1, 11):
Test.create(num=i)
q = Test.select().where(Test.num > 6) | Test.select().where(Test.num > 7)
print(q)
print('Count =', q.count())
for i in q:
print(i.num)
这是它的输出结果。它显示遍历确实返回了4个项目,但计数是错误的:
<class 'DocFinder.DocFinder.DocFinder.test.<locals>.Test'> SELECT t2."id", t2."num" FROM "test" AS t2 WHERE (t2."num" > ?) UNION SELECT t3."id", t3."num" FROM "test" AS t3 WHERE (t3."num" > ?) [6, 7]
Count = 7
7
8
9
10
1 个回答
5
试试用 .wrapped_count()
这个方法吧。