简体   繁体   English

使用peewee检查查询是否存在

[英]check if query exists using peewee

I am using the Peewee library in Python and I want to check if a query exists. 我在Python中使用Peewee库,我想检查查询是否存在。 I do not want to create a record if it doesn't exist, so I don't want to use get_or_create. 我不希望创建一条不存在的记录,因此我不想使用get_or_create。 There must be a better solution than to use try/except with get but I don't see anything. 必须有比使用try / except与get更好的解决方案,但我什么也没看到。 Please let me know if there is a better way. 如果有更好的方法,请告诉我。 Thanks. 谢谢。

You can use .exists() : 您可以使用.exists()

query = User.select().where(User.username == 'charlie')
if query.exists():
    # A user named "charlie" exists.
    cool()

http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=exists#SelectBase.exists http://docs.peewee-orm.com/zh-CN/latest/peewee/api.html?highlight=exists#SelectBase.exists

Alternatively, if you want to check if eg some other table refers this record, you can use WHERE EXISTS (subquery) clause. 另外,如果要检查是否有其他表引用了该记录,则可以使用WHERE EXISTS (subquery)子句。 It is not supported natively by PeeWee, but it can be easily constructed: PeeWee本身不支持它,但是可以很容易地构造它:

subquery = Child.select(Param('1')).where(Child.parent == Parent.id)
parents_with_children = Parent.select().where(
    Clause(SQL('EXISTS'), subquery))

It is equivalent to the following SQL: 它等效于以下SQL:

SELECT * FROM parent
WHERE EXISTS (SELECT 1 FROM child
              WHERE child.parent_id = parent.id);

Here I used SELECT 1 for subquery to avoid fetching unneeded information (like child.id ). 在这里,我child.id查询使用SELECT 1以避免获取不需要的信息(例如child.id )。 Not sure if such optimization is actually required. 不确定是否确实需要这种优化。

If you just need to check existence use the accepted answer. 如果您只需要检查是否存在,请使用接受的答案。

If you are going to use the record if it exists you can make use of Model.get_or_none() as this removes the need to use a try/catch and will not create a record if the record doesn't exist. 如果要使用记录(如果存在),则可以使用Model.get_or_none(),因为这样就无需使用try / catch,并且如果记录不存在也不会创建记录。

class User(peewee.Model):
    username = peewee.CharField(unique=True)

user = User.get_or_none(username='charlie')
if user is not None:
    # found user, do something with it
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM