Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 846
Stefan Weiss Avatar asked Sep 21 '15 09:09

Stefan Weiss


People also ask

Is there a way to save a query in peewee?

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:

How to use SQL helper function in peewee?

In order to implement these SQL functions, Peewee has a SQL helper function fn (). In above example, we used it to find count of records for each city. Following example builds a SELECT query that employs SUM () function. Using Bill and Item tables from models defined earlier, we shall display sum of quantity of each item as entered in Bill table.

Does Peewee support MySQL database?

As mentioned earlier, Peewee supports MySQL database through MySQLDatabase class. However, unlike SQLite database, Peewee can’t create a MySql database. You need to create it manually or using functionality of DB-API compliant module such as pymysql. First, you should have MySQL server installed in your machine.

How do I replace a record in peewee with SQLite?

With SQLite prior to 3.24.0 and MySQL, Peewee offers the replace (), which allows you to insert a record or, in the event of a constraint violation, replace the existing record. class User(Model): username = TextField(unique=True) last_login = DateTimeField(null=True) # Insert or update the user.


Video Answer


1 Answers

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.

like image 79
coleifer Avatar answered Oct 18 '22 02:10

coleifer