- Peewee Tutorial
- Peewee - Home
- Peewee - Overview
- Peewee - Database Class
- Peewee - Model
- Peewee - Field Class
- Peewee - Insert a New Record
- Peewee - Select Records
- Peewee - Filters
- Peewee - Primary & Composite Keys
- Peewee - Update Existing Records
- Peewee - Delete Records
- Peewee - Create Index
- Peewee - Constraints
- Peewee - Using MySQL
- Peewee - Using PostgreSQL
- Peewee - Defining Database Dynamically
- Peewee - Connection Management
- Peewee - Relationships & Joins
- Peewee - Subqueries
- Peewee - Sorting
- Peewee - Counting & Aggregation
- Peewee - SQL Functions
- Peewee - Retrieving Row Tuples/Dictionaries
- Peewee - User defined Operators
- Peewee - Atomic Transactions
- Peewee - Database Errors
- Peewee - Query Builder
- Peewee - Integration with Web Frameworks
- Peewee - SQLite Extensions
- Peewee - PostgreSQL & MySQL Extensions
- Peewee - Using CockroachDB
- Peewee Useful Resources
- Peewee - Quick Guide
- Peewee - Useful Resources
- Peewee - Discussion
Peewee - Defining Database Dynamically
If your database is scheduled to vary at run-time, use DatabaseProxy helper to have better control over how you initialise it. The DatabaseProxy object is a placeholder with the help of which database can be selected in run-time.
In the following example, an appropriate database is selected depending on the application’s configuration setting.
from peewee import * db_proxy = DatabaseProxy() # Create a proxy for our db. class MyUser (Model): name=TextField() city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")]) age=IntegerField() class Meta: database=db_proxy db_table='MyUser' # Based on configuration, use a different database. if app.config['TESTING']: db = SqliteDatabase(':memory:') elif app.config['DEBUG']: db = SqliteDatabase('mydatabase.db') else: db = PostgresqlDatabase( 'mydatabase', host='localhost', port=5432, user='postgres', password='postgres' ) # Configure our proxy to use the db we specified in config. db_proxy.initialize(db) db.connect() db.create_tables([MyUser])
You can also associate models to any database object during run-time using bind() method declared in both database class and model class.
Following example uses bind() method in database class.
from peewee import * class MyUser (Model): name=TextField() city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")]) age=IntegerField() db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='') db.connect() db.bind([MyUser]) db.create_tables([MyUser])
The same bind() method is also defined in Model class.
from peewee import * class MyUser (Model): name=TextField() city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")]) age=IntegerField() db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='') db.connect() MyUser.bind(db) db.create_tables([MyUser])
Advertisements