Single column indexes are defined using field initialization parameters. The following example adds a unique index on the username field, and a normal index on the email field:

    To add a user-defined constraint on a column, you can pass it in using the parameter. You may wish to specify a default value as part of the schema, or add a CHECK constraint, for example:

    1. class Product(Model):
    2. name = CharField(unique=True)
    3. price = DecimalField(constraints=[Check('price < 10000')])
    4. created = DateTimeField(

    Multi-column indexes may be defined as Meta attributes using a nested tuple. Each database index is a 2-tuple, the first part of which is a tuple of the names of the fields, the second part a boolean indicating whether the index should be unique.

    Note

    1. class Meta:
    2. indexes = (
    3. (('first_name', 'last_name'), True), # Note the trailing comma!

    Peewee supports a more structured API for declaring indexes on a model using the method or by directly using the ModelIndex helper class.

    Examples:

    Warning

    SQLite does not support parameterized CREATE INDEX queries. This means that when using SQLite to create an index that involves an expression or scalar value, you will need to declare the index using the helper:

    1. # SQLite does not support parameterized CREATE INDEX queries, so
    2. # we declare it manually.
    3. Article.add_index(SQL('CREATE INDEX ...'))

    For more information, see:

    Peewee allows you to add arbitrary constraints to your , that will be part of the table definition when the schema is created.

    For instance, suppose you have a people table with a composite primary key of two columns, the person’s first and last name. You wish to have another table relate to the people table, and to do this, you will need to define a foreign key constraint:

    You can also implement CHECK constraints at the table level:

    1. class Product(Model):
    2. name = CharField(unique=True)
    3. price = DecimalField()
    4. class Meta: