Repository navigation
Composite primary and foreign keys, one-to-one relation, partial updates, lower memory and bugfixes
Release notes
0.28.0
Highlights:
- Composite primary and foreign keys (#137): mark several fields with
primary_key=True, use foreign keys inside primary keys and relate to link tables keyed by their foreign keys; the key is a tuple (order.pk == (1, 7)) inget(),filter(pk__in=...)and relations. - Partial instance updates with
OrmarConfig(partial_updates=True):update()writes only the passed and changed fields, so changes made in the database since the model was loaded are no longer reverted. Partial updates will become the default in a future release. - Much lower memory and faster startup: importing 60 densely related models takes 13 MiB and 0.13 s instead of 107 MiB and 0.61 s, and
model_dump()/bulk_create()no longer rebuild the relation paths on every call (165 ms → 0.01 ms for a large schema). OneToOnerelations, filteredPrefetch, read-only models for database views and Python 3.15 support.- A batch of relation and
ForwardReffixes.
Please read the Breaking changes before upgrading: upsert(), update()/delete()/load() after a primary key change, nested dicts with a primary key, and Python 3.10 is no longer supported.
✨ Breaking changes
-
upsert()inserts never-saved models whose key is already setupsert()of a model that was never saved but has its primary key set (a uuiddefault, a natural or a composite key) used to run anUPDATEthat matched no row and silently saved nothing (unless__force_save__=Truewas passed). It now looks the row up and inserts it when it's missing. Loaded or saved models are still updated directly.__force_save__is accepted and ignored. #1926country = Country(iso_code="PL", name="Poland") # natural key, never saved # before: an UPDATE matching no row, nothing saved await country.upsert(__force_save__=True) # the workaround # after: SELECT by key, then INSERT (or UPDATE when the row exists) await country.upsert()
-
update(),delete()andload()target the row the model was loaded withAfter changing a model's primary key,
update()moves the row to the new key (UPDATE ... SET id = 5 WHERE id = 1) instead of updating the row with the new key, anddelete()/load()use the original key. #1926album = await Album.objects.get(id=1) album.id = 5 await album.update() # before: UPDATE albums SET ... WHERE id = 5 (row 1 untouched) # after: UPDATE albums SET id = 5, ... WHERE id = 1
To update another row, load it (
await Album.objects.get(id=5)) or useAlbum.objects.filter(id=5).update(...). -
save()raisesModelPersistenceErrorfor a missing primary key value that the database doesn't generate (no autoincrement, no server default), before sending the insert. #1926 -
Primary key and relation internals replaced
The primary key of a model is now described by
ormar_config.pkand the columns connecting two models byfield.link. Model definitions, queries, generated SQL and DDL are unchanged; code using these internals needs updating:Removed Use instead Model.ormar_config.pknameModel.ormar_config.pk.fields(field names)model.pk_columnModel.ormar_config.pk.columns()Model.pk_type()Model.ormar_config.pk.python_type()field.get_related_field_alias(),field.get_related_field_name(),field.get_model_relation_fields()field.link(source_fields(),source_columns(),target_fields(),target_columns())field.to_pk_only,field.construct_pk_only_model()field.to_key_only,field.construct_key_only_model()ormar.fields.foreign_key.create_dummy_instance/create_dummy_modelormar.fields.key_only.key_only_instance/key_only_model_typeForeignKeyConstraintandfield.constraintsforeign keys are built from field.linkormar.queryset.templates.primary_key_column/primary_key_bindModel.ormar_config.pk.columns()/.where_clause()# before pk_name = Album.ormar_config.pkname column = album.pk_column # after (a composite key has several fields and columns) (pk_name,) = Album.ormar_config.pk.fields (column,) = Album.ormar_config.pk.columns()
The statement builders
build_update,build_delete,build_pk_selectandbuild_bulk_updatetakeprimary_key=instead ofpk_column=, andcount_statementtakespk_column_names=(a tuple) instead ofpk_column_name=. #1913 -
A dict with a primary key and nested relations builds a full related model
A related model given as a dict with its primary key and nested relations, e.g.
Writer(notes=[{"id": 2, "letter": {"id": 3}}]), used to be built as a pk-only model, which silently dropped the nested relations. It now builds a full model with them, so its required fields have to be given, or aValidationErroris raised. A dict with only the primary key ({"id": 2}) is still pk-only. #1957 -
Python 3.10 is no longer supported
Python 3.10 reaches end-of-life in October 2026, and the fixes for the
filelockadvisories (GHSA-567q-5qvw-pf92, GHSA-9vhv-jxww-xfm5, GHSA-v4x8-3wr5-3wq8) require Python 3.11 or newer. ormar now requires Python 3.11+. #1904
🆕 Features
-
Composite primary and foreign keys (#137)
ormar maps schemas it didn't design: keys of several columns, foreign keys in primary keys, link tables keyed by their foreign keys and relations to such link tables. Single-column models need no changes (see the breaking changes above for
upsert()andupdate()).class Order(ormar.Model): # PRIMARY KEY (tenant_id, number) ormar_config = base_ormar_config.copy(tablename="orders") tenant_id: int = ormar.Integer(primary_key=True) number: int = ormar.Integer(primary_key=True) class OrderLine(ormar.Model): # FOREIGN KEY (ord_tenant, ord_no) REFERENCES orders ormar_config = base_ormar_config.copy(tablename="order_lines") id: int = ormar.Integer(primary_key=True) order: Optional[Order] = ormar.ForeignKey( Order, columns={"tenant_id": "ord_tenant", "number": "ord_no"} ) order = await Order.objects.create(tenant_id=1, number=7) order.pk # (1, 7) await Order.objects.get(pk=(1, 7)) await OrderLine.objects.create(order=(1, 7)) # a model, dict or key tuple await OrderLine.objects.filter(order__in=[(1, 7), (1, 8)]).all()
What's included:
- Composite primary keys: mark several fields with
primary_key=True. The key value is a tuple (order.pk == (1, 7)) and works inget(pk=...),filter(pk__in=...),exclude(),order_by("pk"), bulk operations andupdate_or_create(pk=...), and in Python-style filters (Order.pk == (1, 7),Order.pk.in_([...]),Order.pk.desc(), also through relations:Book.author.pk == 1). See primary keys. #1926 - Foreign keys in the primary key (
ForeignKey(..., primary_key=True)) for link tables keyed by their foreign keys and for shared primary keys (enrollment.pk == (student.id, course.id));ForeignKey(..., to_field="iso_code")to reference a unique non-pk column;ForeignKey(..., db_constraint=False)to skip the databaseFOREIGN KEYconstraint. See foreign keys in the primary key. #1927 - Foreign keys to models with a composite key, and to a set of unique columns (
to_field=["tenant_id", "sku"]), are stored in several columns (named withcolumns={...}or<field>_<column>by default) under one compositeFOREIGN KEYconstraint. They work in joins, prefetching, filters (order=...,order__in=...,order__isnull=...), bulk operations,values()/values_list()and flattened dumps. See foreign keys to several columns. #1935 - A
ManyToManythroughmodel can declare its own foreign keys to both sides, e.g. an existing link table keyed by them, and ormar uses those fields instead of adding its own. See using an existing link table. #1930 ManyToManyrelations to and from models with a composite key: the generated through table stores each key in several columns. See many to many. #1938- Foreign keys stored in several columns can be part of a primary key, and fields can share a column named in
columns=, so link tables likePRIMARY KEY (tenant_id, member_login, team_code)map directly and work asManyToManythroughmodels. Different values for a shared column raiseModelPersistenceError; a shared column becomesNULLonly when every field storing it isNone. See link tables keyed by foreign keys to several columns. #1939, #1954 ForeignKey,OneToOneandManyToManyrelations to such link tables, andManyToManyrelations declared on them: the referencing side stores one column per key column of the link table (a shared column once). See relations to link tables. #1953
- Composite primary keys: mark several fields with
-
Partial instance updates:
OrmarConfig(partial_updates=True)Model.update(**kwargs)writes every column of the model from memory, so a row changed in the database after the model was loaded (by another request or a worker) has those changes silently reverted. Withpartial_updates=Trueupdate()writes only the passed fields, the fields assigned since the model was loaded or saved (also inpre_updatesignal handlers),Jsonfields mutated in place andon_updatefields; with nothing changed it still writes all columns.update(_partial=True | False)overrides the setting per call.The default,
partial_updates=None, keeps writing all columns but emits aDeprecationWarningwhenupdate(**kwargs)also writes columns that did not change. The default will change to partial updates in a future release: setpartial_updates=Trueto opt in now, orpartial_updates=Falseto keep the old behaviour without the warning.QuerySet.update_or_create()and the relation proxies'update()/update_or_create()(which load the row and update it right away) always write only the changed fields. Closes #1948, see partial updates. #1949base_ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, partial_updates=True ) track = await Track.objects.get(name="The Bird") track.position = 3 await track.update(name="The Bird Strikes Again") # before (and with the default None): UPDATE tracks SET <every column> ... # after: UPDATE tracks SET name=..., position=... WHERE id = ...
-
ormar.OneToOne(to, ...)relation: a unique foreign key whose reverse side holds a single model orNone. Closes #256. See OneToOne. #1934 -
ormar.Prefetch(relation, queryset=...)inprefetch_related()filters, orders and narrows prefetched models with a queryset of the related model. See prefetch with a queryset. #1933 -
Read-only models for database views:
OrmarConfig(view=True). They can be queried, joined and prefetched; writes raise the newReadOnlyModelError, and their tables are kept out ofmetadata.create_all()/ Alembic. Closes #970. See views. #1932 -
Python 3.15 is now supported and tested in CI, and the CI matrix now also covers Python 3.14. #1904
⚡ Performance
- Reverse relations no longer create a full copy of the related model class for every reverse field. Each copy compiled its own pydantic validator and serializer and showed up as a separate model in every later schema, so memory grew roughly with the square of the number of related models. Importing 60 models with dense relations now takes 107 MiB instead of 306 MiB (25 MiB instead of 38 MiB with
defer_build), and a real 45-model application went from 158 MiB to 61 MiB. The annotation of a reverse relation field now refers to the related model itself. #1940 - Registering a reverse relation (or a many to many through model field) no longer rebuilds the pydantic schema of the target model right away, once per relation (a hub model with 44 related models was compiled 44 times, ignoring
defer_build). The model is marked as pending and rebuilt once, with its final fields, when its schema, validator or serializer is first needed: on validation, serialization,model_json_schema(), or when FastAPI or another pydantic model /TypeAdapterbuilds a schema containing it. Importing 60 models with dense relations now takes 13 MiB and 0.13 s instead of 107 MiB and 0.61 s (16 MiB once every model is used; withdefer_build11 MiB and 0.12 s instead of 25 MiB and 0.37 s, 45 MiB instead of 35 MiB once every model is used). #1941 model_dump(),bulk_create(),save_related()andget_pydantic()no longer rebuild the nested map of a model's relation paths on every call. The map is built once per model class and reused, so dumping a model of a densely related schema (91,000 relation paths) takes 0.01 ms instead of 165 ms, andbulk_create()of 300 rows of a model with 12,000 relation paths 17 ms instead of 5.6 s. The cached maps are rebuilt when a relation is registered later, which also fixesmodel_dump(),save_related(),select_all(follow=True)andload_all(follow=True)leaving out relations registered after the model was first used (e.g. the reverse side of a foreign key declared by a model defined later). #1947
🐛 Fixes
- A model with both a concrete relation and a
ForwardRefrelation (e.g.ForeignKey(Author)next toForeignKey(ForwardRef("Book"))) no longer fails at class creation withPydanticUndefinedAnnotation. The related models finish building whenupdate_forward_refs()resolves the reference; before that, other models connected to them already work inmodel_dump(),bulk_create(),save_related()andget_pydantic(), which skip the unresolved relation. #1931, #1952 pklookups other thanpk=(pk__in,pk__gt, ...) failed withKeyError, and ordering bypk(order_by("pk")/order_by("-pk"),ormar_configorder_by=["-pk"], relationorders_by/related_orders_by) produced invalid SQL. Both work for every model now. #1926- The reverse side of a relation is registered when the related model has a field named like the owner model, e.g.
Player.coach = ForeignKey(Coach)next toCoach.fans = ManyToMany(Player, related_name="idols").idolswas silently skipped (Player(idols=...)raisedModelError,coach.fans.add()aKeyError), a field with that name leading to another model raised a falseModelDefinitionError, and with aForwardRefthe model failed withAttributeError: 'ForwardRef' object has no attribute 'ormar_config'. #1958 - A model created before
update_forward_refs()resolved aForwardRefof a related model (failing withPydanticUndefinedAnnotation) works once the reference is resolved. It failed withRecursionErroron every later use. #1955 values()/values_list()return fields with a custom database columnname=(they were left out). #1935- Self-referencing
ManyToManyrelations with explicitthrough_relation_nameandthrough_reverse_relation_nameuse the names as documented on both sides; the primary side swapped them, so the reverse side of the relation returned nothing. #1930 - Models inheriting the same foreign key from an abstract parent no longer share one field object. Queries joining or filtering through that relation from any child but the last one defined (e.g.
select_related("label")) referenced the other child's table and failed withno such column. #1913 - Relations to a model whose primary key is
0work: the foreign key keeps0(it was replaced with-1), non-nullable foreign keys to it can be saved, andprefetch_relatedloads its related rows. #1913 - Pydantic-only fields (
pydantic.Field(...)or plain defaults) on ormar models no longer fail withPydanticUserError: Field ... requires a type annotationon Python 3.14+, where class bodies no longer store__annotations__(PEP 649). #1904 - A related model given as a dict with only its primary key and nested relations (e.g.
Writer(notes=[{"id": 2, "letter": {"id": 3}}])) keeps the nested relations; it was built as a pk-only model, which dropped them. Such a dict now builds a full model, so required fields of that model have to be given (see Breaking changes). #1957