This instructs peewee that whenever a query is executed on Person to use the contacts database.
Note
Take a look at - you will notice that we created a that defined the database, and then extended. This is the preferred way to define a database and create models.
Once the class is defined, you should not access ModelClass.Meta
, but instead use ModelClass._meta
:
>>> Person.Meta
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Person' has no attribute 'Meta'
<peewee.ModelOptions object at 0x7f51a2f03790>
The ModelOptions
class implements several methods which may be of use for retrieving model metadata (such as lists of fields, foreign key relationships, and more).
Here is an example showing inheritable versus non-inheritable attributes:
>>> db = SqliteDatabase(':memory:')
... class Meta:
... database = db
... table_name = 'model_one_tbl'
...
... pass
...
>>> ModelOne._meta.database is ModelTwo._meta.database
True
>>> ModelOne._meta.table_name == ModelTwo._meta.table_name
False
The Meta.primary_key
attribute is used to specify either a or to indicate that the model has no primary key. Composite primary keys are discussed in more detail here: .
To indicate that a model should not have a primary key, then set primary_key = False
.
Examples:
Table Names
By default Peewee will automatically generate a table name based on the name of your model class. The way the table-name is generated depends on the value of Meta.legacy_table_names
. By default, legacy_table_names=True
so as to avoid breaking backwards-compatibility. However, if you wish to use the new and improved table-name generation, you can specify legacy_table_names=False
.
Attention
To preserve backwards-compatibility, the current release (Peewee 3.x) specifies legacy_table_names=True
by default.
In the next major release (Peewee 4.0), legacy_table_names
will have a default value of False
.
To explicitly specify the table name for a model class, use the table_name
Meta option. This feature can be useful for dealing with pre-existing database schemas that may have used awkward naming conventions:
class UserProfile(Model):
table_name = 'user_profile_tbl'
If you wish to implement your own naming convention, you can specify the Meta option. This function will be called with your model class and should return the desired table name as a string. Suppose our company specifies that table names should be lower-cased and end with “_tbl”, we can implement this as a table function: