Stefan Weiss
Stefan Weiss

Reputation: 461

How to get sql query from peewee?

Simple peewee example: MySQL DB "Pet" with autoincrement "id" and char-field "name".

Doing

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

With .sql() we get the sql interpretation.

How to get the raw sql query from:

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

?

Upvotes: 8

Views: 15441

Answers (3)

You can use python's "%" operator to build the string


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))


Upvotes: 0

Mart Van de Ven
Mart Van de Ven

Reputation: 379

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. Mogrify is provided by the psycopg2 library and hence may not be available when connecting to other databases.

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.

Upvotes: 1

coleifer
coleifer

Reputation: 26235

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().

If you want the SQL for a query like Model.create(), then you should look into using Model.insert() instead:

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.

Upvotes: 8

Related Questions