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')
?
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:
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With