”;
An object of Model sub class in Peewee API corresponds to a table in the database with which connection has been established. It allows performing database table operations with the help of methods defined in the Model class.
A user defined Model has one or more class attributes, each of them is an object of Field class. Peewee has a number of subclasses for holding data of different types. Examples are TextField, DatetimeField, etc. They correspond to the fields or columns in the database table. Reference of associated database and table and model configuration is mentioned in Meta class. Following attributes are used to specify configuration −
Meta class Attributes
The meta class attributes are explained below −
Sr.No | Attribute & Description |
---|---|
1 |
Database
Database for model. |
2 |
db_table
Name of the table to store data. By default, it is name of model class. |
3 |
Indexes
A list of fields to index. |
4 |
primary_key
A composite key instance. |
5 |
Constraints
A list of table constraints. |
6 |
Schema
The database schema for the model. |
7 |
Temporary
Indicate temporary table. |
8 |
depends_on
Indicate this table depends on another for creation. |
9 |
without_rowid
Indicate that table should not have rowid (SQLite only). |
Following code defines Model class for User table in mydatabase.db −
from peewee import * db = SqliteDatabase(''mydatabase.db'') class User (Model): name=TextField() age=IntegerField() class Meta: database=db db_table=''User'' User.create_table()
The create_table() method is a classmethod of Model class that performs equivalent CREATE TABLE query. Another instance method save() adds a row corresponding to object.
from peewee import * db = SqliteDatabase(''mydatabase.db'') class User (Model): name=TextField() age=IntegerField() class Meta: database=db db_table=''User'' User.create_table() rec1=User(name="Rajesh", age=21) rec1.save()
Methods in Model class
Other methods in Model class are as follows −
Sr.No | Model Class & Description | 1 |
Classmethod alias()
Create an alias to the model-class. It allows the same Model to any referred multiple times in a query. |
---|---|
2 |
Classmethod select()
Performs a SELECT query operation. If no fields are explicitly provided as argument, the query will by default SELECT * equivalent. |
3 |
Classmethod update()
Performs an UPDATE query function. |
4 |
classmethod insert()
Inserts a new row in the underlying table mapped to model. |
5 |
classmethod delete()
Executes delete query and is usually associated with a filter by where clause. |
6 |
classmethod get()
Retrieve a single row from mapped table matching the given filters. |
7 |
get_id()
Instance method returns primary key of a row. |
8 |
save()
Save the data of object as a new row. If primary-key value is already present, it will cause an UPDATE query to be executed. |
9 |
classmethod bind()
Bind the model to the given database. |
”;