By defining an ormar Model you get corresponding Pydantic model as well as Sqlalchemy table for free.
They are being managed in the background and you do not have to create them on your own.
Model Class
To build an ormar model you simply need to inherit a ormar.Model class.
Names of the fields will be used for both the underlying pydantic model and sqlalchemy table.
Dependencies
Since ormar depends on databases and sqlalchemy-core for database connection
and table creation you need to assign each Model with two special parameters.
importdatabasesimportsqlalchemyimportormardatabase=databases.Database("sqlite:///db.sqlite")metadata=sqlalchemy.MetaData()classCourse(ormar.Model):classMeta:# if you omit this parameter it will be created automatically# as class.__name__.lower()+'s' -> "courses" in this exampletablename="my_courses"database=databasemetadata=metadataid:ormar.Integer(primary_key=True)name:ormar.String(max_length=100)completed:ormar.Boolean(default=False)
Constraints
On a model level you can also set model-wise constraints on sql columns.
Right now only UniqueColumns constraint is present.
Tip
To read more about columns constraints like primary_key, unique, ForeignKey etc. visit fields.
You can set this parameter by providing Meta class constraints argument.
importdatabasesimportsqlalchemyimportormardatabase=databases.Database("sqlite:///db.sqlite")metadata=sqlalchemy.MetaData()classCourse(ormar.Model):classMeta:database=databasemetadata=metadata# define your constraints in Meta class of the model# it's a list that can contain multiple constraints# hera a combination of name and column will have to be unique in dbconstraints=[ormar.UniqueColumns('name','completed')]id=ormar.Integer(primary_key=True)name=ormar.String(max_length=100)completed=ormar.Boolean(default=False)
Initialization
There are two ways to create and persist the Model instance in the database.
Tip
Use ipython to try this from the console, since it supports await.
If you plan to modify the instance in the later execution of your program you can initiate your Model as a normal class and later await a save() call.
importdatabasesimportsqlalchemyimportormardatabase=databases.Database("sqlite:///db.sqlite")metadata=sqlalchemy.MetaData()classCourse(ormar.Model):classMeta:database=databasemetadata=metadataid=ormar.Integer(primary_key=True)name=ormar.String(max_length=100)completed=ormar.Boolean(default=False)course=Course(name="Painting for dummies",completed=False)awaitcourse.save()awaitCourse.objects.create(name="Painting for dummies",completed=False)
If you want to initiate your Model and at the same time save in in the database use a QuerySet's method create().
For creating multiple objects at once a bulk_create() QuerySet's method is available.
Each model has a QuerySet initialised as objects parameter
importdatabasesimportsqlalchemyimportormardatabase=databases.Database("sqlite:///db.sqlite")metadata=sqlalchemy.MetaData()classCourse(ormar.Model):classMeta:database=databasemetadata=metadataid=ormar.Integer(primary_key=True)name=ormar.String(max_length=100)completed=ormar.Boolean(default=False)course=Course(name="Painting for dummies",completed=False)awaitcourse.save()awaitCourse.objects.create(name="Painting for dummies",completed=False)
Info
To read more about QuerySets (including bulk operations) and available methods visit queries
Model methods
load
By default when you query a table without prefetching related models, the ormar will still construct
your related models, but populate them only with the pk value.
1
2
3
4
5
6
7
track=awaitTrack.objects.get(name='The Bird')track.album.pk# will return malibu album pk (1)track.album.name# will return None# you need to actually load the data firstawaittrack.album.load()track.album.name# will return 'Malibu'
save
delete
update
Internals
Apart from special parameters defined in the Model during definition (tablename, metadata etc.) the Model provides you with useful internals.
Pydantic Model
All Model classes inherit from pydantic.BaseModel so you can access all normal attributes of pydantic models.
For example to list pydantic model fields you can: