Schema Creation¶
Here we create connection to SQLite database client and then we discover & initialize models.
-
async classmethod Tortoise.generate_schemas(safe=
True)[source] Generate schemas according to models provided to
.init()method. Will fail if schemas already exists, so it’s not recommended to be used as part of application workflow- Parameters:¶
- safe=
True¶ When set to true, creates the table only when it does not already exist.
- safe=
- Raises:¶
ConfigurationError – When
.init()has not been called.- Return type:¶
None
generate_schema generates schema on empty database.
There is also the default option when generating the schemas to set the safe parameter to True which will only insert the tables if they don’t already exist.
Non-default Database Schemas¶
Tortoise ORM supports placing tables in non-default database schemas on PostgreSQL and MSSQL
(on MySQL, schema maps to a separate database name via `` db.`table` `` syntax).
Set the schema attribute in a model’s Meta class:
class Product(Model):
name = fields.CharField(max_length=200)
class Meta:
schema = "catalog"
class Inventory(Model):
product = fields.ForeignKeyField("models.Product")
quantity = fields.IntField()
class Meta:
schema = "warehouse"
Cross-schema foreign keys work automatically. The migration framework also handles schema-qualified tables, including schema creation when needed.