Skip to content

common parameters

All field types have a common set of parameters.

major key

Primary_key: bool = False -> Default is False.

Sets the primary key column on the table, and the foreign key always references the pk of the model.

Used only in sql.

autoincrement n.

Autoincrement: bool = Primary_key and type == int -> True if column is primary key and type is Integer, False otherwise.

Can only be used with int/bigint fields.

If the field has autoincrement, it becomes optional.

Used in sql and pydantic (change pk field to optional field for autoincrement).

may be empty

Nullable: bool = False -> Default to False for all fields except relationship fields.

Automatically changes to True if the user provides one of the following:

  • Provide default values or functions
  • server_default value or function provided
  • Set autoincrement on the Integrprimary_key field

Specifies whether fields are optional or required, used with sql and pydantic.

By default, for pydantic and sqlalchemy, as these are the most common settings:

  • nullable=False -indicates that the database column is not empty and that fields are required in pydantic
  • nullable=True -indicates that the database column is empty and the field is optional in pydantic

If you want to set different settings for pydantic and database, see sql_nullable below.

!!!Note that all foreign keys can also be empty by default, meaning that no correlation model is required.

1
If you change the `ForeignKey` column to `nullable=False`, it becomes required.

sql_nullable

sql_nullable: bool = nullable -> defaults to a nullable value (as described above).

Specifies whether fields are not null or only null is allowed in the database.

Use this setting in conjunction with nullable only if you want to set different options in your pydantic model and database.

An example usage might be to make a field non-null in the database, but allow the field to be nullable in pydantic (i.e., using the server_default value). This prevents the field from updating to null (as with the server_default setting, you cannot insert a null value because the default value will be used)

default

Default: Any = None -> Default is None.

If no other value is passed, the default value is used.

Used during pydantic model definition in sql invoked at insert time.

If the field has a default value, it becomes optional.

You can pass static values or callable (functions, etc.)

Used in both sql and pydantic.

Example of use:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# note the distinction between passing a value and Callable pointer

# value
name: str = ormar.String(max_length=200, default="Name")

# note that when you call a function it's not a pointer to Callable
# a definition like this will call the function at startup and assign
# the result of the function to the default, so it will be constant value for all instances
created_date: datetime.datetime = ormar.DateTime(default=datetime.datetime.now())

# if you want to pass Callable reference (note that it cannot have arguments)
# note lack of the parenthesis -> ormar will call this function for you on each model
created_date: datetime.datetime = ormar.DateTime(default=datetime.datetime.now)

# Callable can be a function, builtin, class etc.

server default

server_default: Any = None -> Default is None.

If no other value is passed, the default value is used.

In sql invoked on the server side, so you can pass ie sql functions (such as now() or queries/values wrapped in sqlalchemy text() clauses).

If this field has a server_default value, it becomes optional.

You can pass static values or callable (functions, etc.)

Used only in sql.

Example of use:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from datetime import datetime

import databases
import ormar
import sqlalchemy
from sqlalchemy import func, text

database = databases.Database("sqlite:///test.db")
metadata = sqlalchemy.MetaData()


class Product(ormar.Model):

    ormar_config = ormar.OrmarConfig(
        database=database, metadata=metadata, tablename="product"
    )

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)
    company: str = ormar.String(max_length=200, server_default="Acme")
    sort_order: int = ormar.Integer(server_default=text("10"))
    created: datetime = ormar.DateTime(server_default=func.now())

!!! warning server_default accepts str,sqlalchemy.sql.elements.ClauseElement, or sqlalchemy.sql.elements.TextClause So if you want to set the ie integer value, you need to wrap it in sqlalchemy.text() function, as shown above

!!!Tip You can also pass a valid sql (dialect-specific) contained in sqlalchemy.text()

1
For example `func.now()` above could be exchanged for `text('(CURRENT_TIMESTAMP)')` for sqlite backend

!!!info server_default is passed directly to sqlalchemy table definitions, so you can read more in the server default sqlalchemy documentation

name

name: str = None -> Default is None

Allows you to specify column name aliases to use.

Useful for existing database structures that use reserved keywords, or if you want to use a database name different from the ormar field name.

Take the following code snippet for example.

From as a reserved word in python prevents you from creating models using that column name.

Changing the model name to from_and adding the parameter name ='from 'causes ormar to use from as the database column name.

1
2
 #... rest of Model cut for brevity
 from_: str = ormar.String(max_length=15, name='from')

Similarly, you can change the foreign key column name in the database while retaining the desired relationship name in ormar:

1
2
 # ... rest of Model cut for brevity
album: Optional[Album] = ormar.ForeignKey(Album, name="album_id")

index

Index: bool = False -> Default is False,

Sets the index of a table column.

Used only in sql.

unique

Bool = False

Sets unique constraints on table columns.

Used only in sql.

Override_pydantic_type

By default, ormar uses a predefined pydantic field type that applies to model creation (so type hinting is optional).

If you wish, you can apply your own type, which will completely replace the built-in type. Therefore, as a user, it is your responsibility to provide a valid type in the context of a given ormar field type.

Warning Note that by default, you should use built-in parameters passed to the underlying pydantic field.

1
You can check what arguments are supported in field types section or in [pydantic](https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation) docs.

!!!Dangerously setting the wrong type of pydantic field can corrupt your model, so override it only if you know what you're doing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
As it's easy to break functionality of ormar the `overwrite_pydantic_type` argument is not available on relation fields!


base_ormar_config = ormar.OrmarConfig(
    metadata=metadata
    database=database
)


# sample overwrites
class OverwriteTest(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="overwrites")

    id: int = ormar.Integer(primary_key=True)
    my_int: str = ormar.Integer(overwrite_pydantic_type=PositiveInt)
    constraint_dict: Json = ormar.JSON(
        overwrite_pydantic_type=Optional[Json[Dict[str, int]]])