简体   繁体   English

如何从peewee获取sql查询?

[英]How to get sql query from peewee?

Simple peewee example: MySQL DB "Pet" with autoincrement "id" and char-field "name".简单的 peewee 示例:带有自动增量“id”和字符字段“name”的 MySQL 数据库“Pet”。

Doing正在做

my_pet = Pet.select().where(name == 'Garfield')

With .sql() we get the sql interpretation.使用 .sql() 我们得到 sql 解释。

How to get the raw sql query from:如何从以下位置获取原始 sql 查询:

my_pet = Pet.get(name='Garfield')

? ?

When you write:当你写:

my_pet = Pet(name='Garfield')

Nothing at all happens in the database.数据库中什么也没有发生。

You have simply created an object.您只是创建了一个对象。 There is no magic, as peewee is an ActiveRecord ORM, and only saves when you call a method like Model.save() or Model.create() .没有魔法,因为 peewee 是一个 ActiveRecord ORM,并且仅在您调用Model.save()Model.create()类的方法时才保存。

If you want the SQL for a query like Model.create() , then you should look into using Model.insert() instead:如果您想要 SQL 用于Model.create()类的查询,那么您应该考虑使用Model.insert()代替:

insert_stmt = Pet.insert(name='Garfield')
sql = insert_stmt.sql()
new_obj_id = insert_stmt.execute()

The downside there is that you aren't returned a model instance, just the primary key.缺点是您没有返回模型实例,只是主键。

If you are connecting to a Postgres database, per peewee 3.13 you can print SQL queries by first getting the cursor, then calling mogrify() for your query.如果您要连接到 Postgres 数据库,根据 peewee 3.13您可以通过首先获取游标,然后为您的查询调用mogrify()来打印 SQL 查询。 Mogrify is provided by the psycopg2 library and hence may not be available when connecting to other databases. Mogrify 由psycopg2库提供,因此在连接到其他数据库时可能不可用。

Given your example:鉴于你的例子:

my_pet = Pet.select().where(Pet.name == 'Garfield').limit(1)

cur = database.cursor()
print(cur.mogrify(*my_pet.sql()))

Where database is the Peewee Database object representing the connection to Postgres.其中database是表示与 Postgres 的连接的 Peewee 数据库对象。

You can use python's "%" operator to build the string您可以使用 python 的“%”运算符来构建字符串


def peewee_sql_to_str(sql):
    return (sql[0] % tuple(sql[1]))

insert_stmt = Pet.insert(name='Garfield')
sql = insert_stmt.sql()

print(peewee_sql_to_str(sql))


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

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