问题描述
我有模型类A
和B
代表两个具有不同列的表,但是两个表都包含一个code
列。现在,我要检查这些表之一中是否不存在给定的代码candidate
。
在peewee中,我想到要选择code
和A
的{{1}}列,将UNION都选择为B
并在{{1 }}:
AB
这将导致错误AB
。根据peewee-docs的说法,candidate = 'randomCode'
AB = A.select(A.code) | B.select(B.code)
if not AB.select().where(AB.c.code == candidate).exists():
print('candidate does not exist')
需要一个数据库,但是即使使用它作为参数,该错误似乎也会传播到基础功能:peewee.InterfaceError: Query must be bound to a database in order to call "exists"
。
我更加困惑,因为对一个表的存在检查就像一个超级按钮,而没有将数据库作为显式参数:
exists()
现在,我通过对peewee.InterfaceError: Query must be bound to a database in order to call "scalar"
和candidate = 'randomCode'
if not A.select().where(A.code == candidate).exists():
print('candidate does not exist')
进行两个单独的存在性检查并得出结果来解决了这个问题。尽管如此,我还是想知道我到底在做什么错,以及对于CompositeSelectQuery如何解决此问题,我认为这会整整齐齐。
解决方法
我认为您做错了什么。对我来说很好:
from peewee import *
db = SqliteDatabase(':memory:')
class Base(Model):
class Meta:
database = db
class A(Base):
a = TextField()
class B(Base):
b = TextField()
db.create_tables([A,B])
qa = A.select()
qb = B.select()
qu = qa | qb
print(qu.exists())
A.create(a='a')
print(qu.exists())