Release notes
0.30.0
✨ Breaking changes
-
Relations are traversed from the loaded instances, not from a precomputed relation map (#1998)
model_dump(),save_related(),get_pydantic()andselect_all(follow=True)/load_all(follow=True)decided which relations to follow from a relation tree cached on each model class. On densely related schemas (4+ models related to each other) that tree left out valid paths and contained paths with a model twice on them, and building it correctly grows exponentially. The default relation map is now decided per node from the set of models on the current path (a relation is followed unless its target is already on the path, a direct self relation once), and the nodes are shared and cached per class (at most 256 per class). Where the old tree was right the output is identical.The old behaviour stays available for one release with
ORMAR_RELATION_TRAVERSAL=map(environment variable) orormar.models.traversal.set_relation_traversal(mode="map"). Selecting it emits aDeprecationWarning; themapmode and the relation tree are removed in 0.31.0. -
follow=Truefollows forward foreign keys, 5 levels deep (#1998)select_all(follow=True)andload_all(follow=True)followed every relation without a limit, which on dense schemas meant hundreds of thousands of joins and multiplied rows. They now follow foreign keys and one to one relations of the model (nullable ones too) up tomax_depthlevels (default 5), so the joins never multiply rows. Reverse foreign keys and many to many relations are loaded withfollow_reverse=N(they are followed in the first N levels,True= 1) or by naming them inselect_related(). Unlike Django'sselect_related()without arguments, nullable foreign keys are followed, as ormar foreign keys are nullable by default.Python 1 2
await Department.objects.select_all(follow=True, follow_reverse=2).get() await chapter.load_all(follow=True, max_depth=2) -
Table aliases in generated SQL change (#1998)
Joined tables and their column labels are prefixed with a 10 hex digit hash of the relation path instead of 6 (
t6bba8518ed_albumsinstead oft1b26c7_albums), so two paths of one query practically never share an alias. Only code that matches on the raw SQL text (tests asserting SQL, query log filters) is affected. -
get_pydantic()generates one named nested model per model (#1998)Nested relations point to a nested model of the related model (
Book_nested), so cycles become recursive models ($refin OpenAPI) instead of a fixed-depth copy of the tree. Relation fields of nested models are optional and include the relation back to the parent; the root model keeps its required/optional rules. Names no longer have a random suffix and do not depend on the order of calls (Book,Book_nested,Book_depth2, a hash suffix forinclude/exclude/flatten_fields), so the OpenAPI document is stable between runs. New parameters:max_depth=limits nesting,omit_back_relations=Trueleaves the relation back to the parent out of nested models (closer to the old shape, more models). Generated models validate an ormar instance through itsmodel_dump(), so returning an instance from a FastAPI endpoint does not loop over its relations. This also fixes the cached nested model of a class being reused under every parent (Author.get_pydantic()followed byBook.get_pydantic()returnedBookwithoutauthor).Migration: if a response must keep exactly one level of nesting use
get_pydantic(max_depth=1); ifselect_all(follow=True)/load_all(follow=True)must load reverse or many to many relations passfollow_reverse=Nor list them inselect_related(); for deeper forward chains passmax_depth=. -
values()andvalues_list()join the relations of selected related fields (#2005)Related fields they select (e.g.
values(["name", "category__name"]), also afterfields()) are joined like in filters. Withoutselect_related()those fields used to be silently dropped. As withselect_related(), a reverse or many to many relation returns one row per related model, so such queries can return more rows than before. -
ormar.Enumforwardssqlalchemy.Enumoptions (#1385, #1987)values_callable,native_enum,create_constraint,length,validate_strings,schema,metadata,inherit_schemaandquoteare passed to the column type. They used to be accepted and silently dropped, so e.g. anintenum withvalues_callablestored member names ("UK") instead of values. If you passed any of them, check the generated DDL and the stored data: rows written as names are not read back withvalues_callable.
🆕 Features
-
update()anddelete()with related models (#1967, #1973)update()anddelete()accept filters on related models of any kind (forward, reverse, many to many) and touch the rows the same filters select inall(), instead of raisingQueryDefinitionError. Expressions inupdate()can read fields of models reached through foreign keys; rows with aNULLforeign key on the path are not updated. See update.Python 1 2
await Booking.objects.filter(training__instructor=instructor).delete() await Track.objects.filter(album__name="A").update(position=F("album__rank")) -
Greatest,LeastandCoalescein column expressions (#1974, #1977)Functions for filters and
update(), e.g. atomic "never go back" or "never below zero" updates. On SQLiteGreatest/Leastcompile to the scalarmax()/min(); with aNULLargument PostgreSQL ignores it, MySQL and SQLite returnNULL. See update.Python 1 2
await Member.objects.filter(id=1).update(read_id=Greatest(F("read_id"), newest)) await Pass.objects.filter(id=1).update(refunded=Coalesce(F("refunded"), 0) + amount) -
Random()in column expressions (#1977)A random float in
[0, 1)per row for filters andupdate(), also accepted byorder_by()like"?"andormar.random().Python 1await Player.objects.update(each=True, score=Random()) -
Atomic upsert with
create(on_conflict="update")(#1975, #1978)Inserts the row or updates the one it conflicts with on
conflict_target, in one statement, and returns the stored row. Unlikeupdate_or_create()concurrent calls neither fail nor overwrite each other.pre_save/post_saveare sent in both cases. See conflict handling.Python 1 2 3 4
device = await Device.objects.create( endpoint_hash=h, keys=k, on_conflict="update", conflict_target=["endpoint_hash"], update_fields=["keys"], ) -
update_returning(): update rows and get them back (#1986)QuerySet.update_returning(each=False, **kwargs)(and onQuerysetProxy) updates likeupdate(), with the same filters and expressions, and returns the updated models as stored, with their own columns. PostgreSQL and SQLite (3.35+) run oneUPDATE ... RETURNING; MySQL locks the rows withSELECT ... FOR UPDATE, updates them by primary key and reads them back in one transaction.update()is unchanged. See update_returning.Python 1 2 3
expired = await Booking.objects.filter(status="waitlisted").update_returning( status="expired" ) -
Expressions on conflict with
update_values(#1985)create()andbulk_create()withon_conflict="update"takeupdate_values: values or column expressions set on the conflicting row in the same statement, e.g. an atomic counter or a "never go back" marker.F("x")is the existing row's column, the newormar.Inserted("x")the value the insert tried to write (excluded.x,VALUES(x)on MySQL). Withupdate_valuestheupdate_fieldsdefault to none;on_updatefields not named in either still get their value. The rules of expressions inupdate()apply, the statement is cached per expression shape, and MySQL bulk upserts keep their single batch. See expressions on conflict.Python 1 2 3 4 5 6 7 8 9 10
await TrackLevel.objects.create( track=track, level=3, completed=1, on_conflict="update", conflict_target=["track", "level"], update_values={"completed": F("completed") + 1}, ) await Member.objects.create( chat=chat, user=user, read_id=message_id, on_conflict="update", conflict_target=["chat", "user"], update_values={"read_id": Greatest(F("read_id"), Inserted("read_id"))}, ) -
Enums stored by value with
ormar.Enum(store_values=True)(#1991)An
intenum gets anINTEGERcolumn with a check constraint on its values instead of a string enum column, so the database holds1,2and compares them as numbers. Other enums store their values instead of member names.Python 1 2 3 4 5 6
class Country(IntEnum): UK = 1 US = 2 country: Country = ormar.Enum(enum_class=Country, store_values=True) # country INTEGER NOT NULL CHECK (country IN (1, 2)) -
Unsigned integers with
unsigned=True(#1015, #1992)Integer,BigIntegerandSmallIntegeracceptunsigned=True: the column isUNSIGNEDon MySQL and MariaDB (foreign keys to it too), getsCHECK (column >= 0)on PostgreSQL and SQLite, andminimumdefaults to0. Alembic autogenerate no longer recreates columns that were made unsigned by hand. -
Rows as tuples from the query executor (#1983)
fetch_all()andfetch_one()ofdatabase.get_query_executor()takeas_tuples=Trueand return tuples of values in select order instead of rows keyed by result label, with the same type conversion.Python 1 2 3
async with database.get_query_executor() as executor: rows = await executor.fetch_all(select(users.c.id, users.c.name), as_tuples=True) # -> [(1, "a"), (2, "b")]
🐛 Fixes
OrmarConfig(constraints=[...])andormar_config.copy(constraints=[...])acceptIndexColumnsfor type checkers. The annotation waslist[ColumnCollectionConstraint], whichIndexColumns(a subclass ofsqlalchemy.Index) is not, so mypy rejected it although it worked at runtime. #1982fetch_val(query, column=...)of the query executor returned the first column for anycolumnwhen the statement ran through SQLAlchemy (drivers without native execution,native_execution=False); it returns the requested column now. #1984- Two relation paths of one query whose table aliases had the same hash raised
QueryDefinitionError: Alias ... collides with an already joined relation(since 0.27.0, aliases were a 24 bit hash of the relation path). Rare for one query, but likely with many joins (about 11 % for 2,000 joins). Aliases are now a 40 bit hash (0.0002 % for 2,000 joins), and a remaining collision is resolved: every alias is owned by the first path that gets it and a colliding path gets the next free salted hash. #1998
📝 Docs
- SQLAlchemy core statements: how to run core statements on ormar's connection and in its transactions with
database.get_query_executor(), what its methods return and how to turn the rows back into models. See SQLAlchemy core statements. #1984
⚡ Performance
-
Relation trees keep their size with densely related models (#1995, #1996)
The relation tree behind
model_dump(),save_related()andget_pydantic()(only used by the deprecatedmaptraversal since #1998) was built by spelling out every relation path of the model, and the number of paths grows exponentially with how densely models are related (self references, several relations to the same model, reverse relations). It was cached on each model class, so a class could keep tens of megabytes for the life of the process. The tree is now built directly and a repeated subtree is stored once: 7 models related to each other through foreign keys and many to many relations take 0.02 MB and 3 ms instead of 64 MB and 1.2 s per class. The tree has the same content; the flat list of paths is only built forload_all(follow=True)andselect_all(follow=True). * Upserts reuse their compiled statement (#1979, #1980)SQLAlchemy gives no cache key to inserts with
ON CONFLICT/ON DUPLICATE KEY, socreate(on_conflict=...)andbulk_create(on_conflict=...)compiled their statement on every call and asyncpg prepared it again for a single row. Statements without a cache key now keep their plan per statement object (bounded like the other plans): a one-row upsert on PostgreSQL takes one round trip instead of up to three. * MySQL bulk upserts withon_updatefields run as one batch (#1979, #1980)bulk_create(on_conflict="update")of a model withon_updatefields ran one statement per row on MySQL. Theon_updatevalues are now set once in user variables, so the rows go in one multi-row insert.
📦 Dependencies
- SQLAlchemy 2.1 supported, the range is now
>=2.0.50,<2.2. Native execution reads the asyncpg transaction state the way both versions do, and an emptyexecute_many()no longer passes the empty parameter list SQLAlchemy 2.1 deprecates. The lower bound goes up from 2.0.40, because ormar 0.29 already needed 2.0.50 (asyncmy error translation and asyncpg disconnects failed on older releases); CI now also runs the suite on 2.0.50. #1981
0.29.0
🆕 Features
-
select_for_update()row locks (#781, #1963)Locks the rows of the queried model until the end of the transaction, with
nowait,skip_locked,read(FOR SHARE) andno_key(PostgreSQLFOR NO KEY UPDATE/FOR KEY SHARE) options. It raisesQueryDefinitionErroroutside a transaction and with count, exists and aggregates; on SQLite it's a no-op. See transactions.Python 1 2
async with database.transaction(): jobs = await Job.objects.select_for_update(skip_locked=True).order_by("id").limit(10).all() -
Column expressions in filters and
update()(#782, #1962)Field accessors and the new
ormar.F("field")combine with+,-and*into expressions the database evaluates: compare two columns in a filter, also of related models (joined automatically), or update a column from its own value in one statement, so concurrent updates are not lost.Python 1 2 3 4
await Slot.objects.filter(taken__lt=F("capacity")).all() await Slot.objects.filter(taken__lt=F("owner__limit")).all() await Slot.objects.filter(Slot.taken < Slot.capacity).all() await Slot.objects.filter(id=1, taken__lt=F("capacity")).update(taken=Slot.taken + 1) -
nefilter operator (#1962)filter(name__ne="a")andModel.name != "a"filter by not equal (IS NOT NULLforNone), also with column expressions (filter(taken__ne=F("capacity"))). A trailingneis now always the operator, like the other operators: filter a field namednewithne__exact=...(location__ne=5compares thelocationkey, notlocation.ne). -
Conflict handling in
create()andbulk_create()(#1016, #1437, #1964)create(on_conflict="ignore")skips a row that conflicts with an existing one on any unique key and returnsNoneinstead of raisingIntegrityError, so concurrent creates of the same row no longer fail.bulk_create(on_conflict="ignore")skips such rows, andbulk_create(on_conflict="update", conflict_target=[...], update_fields=[...])updates the existing rows (an upsert). See conflict handling. -
order_by("?")ororder_by(ormar.random())orders the rows randomly (random(),rand()on MySQL and MariaDB), also withlimit(),select_related(), relations andPrefetchquerysets.Python 1winners = await User.objects.order_by(ormar.random()).limit(3).all()
🐛 Fixes
get_or_create()(also on relations) insidedatabase.transaction()now runs the insert in a savepoint. On PostgreSQL a lost race used to abort the whole transaction and raiseInFailedSQLTransactionError; now it returns the concurrent caller's row, and an unrelated constraint error is raised asIntegrityErrorwith the transaction still usable. #1960prefixed_table()(ormar.relations.aliases) takes keyword arguments only. A positional call, e.g. when building a customwhere()on aselect_related()query, returned a second aliased table under the same name, so PostgreSQL failed withtable name "..." specified more than once; it raises aTypeErrornow. The other cached helpersbuild_prefixed_columns(),build_shared_row_plan()andkey_dict_type()are keyword-only too. #1961order_by()withnulls_orderingon amariadb://database URL emulatesNULLS FIRST/NULLS LASTlike on MySQL; it used to emit theNULLSclause, which MariaDB rejects. #1966- Paths to the through model of a many to many relation that omit the relation (e.g.
postcategory__sort_orderfromPost) now resolve like the explicitcategories__postcategory__sort_order: filters join the relation instead of producing a cross join, andupdate()/delete()reject them like other related filters. In a many to manyPrefetchqueryset, ordering by a through field raises a clearQueryDefinitionError(it was an SQL "no such column" error) and filtering on one, which used to be silently ignored, is rejected. Aggregates on through fields no longer raiseKeyErrorfor a single column, and multi-column results are keyed by the requested paths. #1962
0.28.0
✨ 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. #1926Python 1 2 3 4 5
country = 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. #1926Python 1 2 3 4 5
album = 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 = 1To 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()Python 1 2 3 4 5 6
# 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()).Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
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. #1949Python 1 2 3 4 5 6 7 8 9
base_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
0.27.0
✨ Breaking changes
-
Query results share related models across rows
A related model reached through the same relation with the same pk is now one instance in the whole query result, the same way
prefetch_relatedalready loads them. Previously each joined row got its own copy. WithChapter.objects.select_related("book").all():chapters[0].book is chapters[1].bookfor chapters of the same book, so changing one of them is visible through all of them.- Reverse relations of a shared model list every loaded row:
chapter.book.chapterscontains all loaded chapters of that book, not only the one it was reached from, so code iterating those relations sees all of them.
The same applies to pk-only models of relations that are not selected: with
Chapter.objects.all(), chapters of the same book share onebookinstance with only its pk set, so loading it withawait chapter.book.load()fills it in for all of them.Models reached through a many-to-many relation stay separate per parent, so each keeps its own through model, and the same model on two different relations (e.g.
authorandeditor) stays two instances. Serialized results (model_dump(), FastAPI responses) are unchanged. If you relied on per-row copies, take an independent one withmodel_copy()before changing it. #1851
✨ Features
DatabaseConnection.connect()opens the whole connection pool up front, so the first concurrent queries after startup don't pay for opening connections (about 30 ms each on a local PostgreSQL).min_connections=Nopens up toNinstead (at mostpool_size), andmin_connections=0keeps the lazy pool. As a resultconnect()now raises when the database is unreachable, instead of the first query; passmin_connections=0to keep connecting lazily, e.g. when the application can start before its database. Listeners for SQLAlchemy'sconnectevent (pragmas, session settings) added to the engine afterconnect()miss the connections opened up front, so register them on the pool class beforehand or passmin_connections=0.asyncmyis now the recommended MySQL driver (mysql+asyncmy://...) andpip install ormar[mysql]installs it alongsideaiomysqlandpymysql. On MySQL it is ~1.2× faster overall and up to 2.5× faster when fetching larger result sets thanaiomysql, which stays supported, so existingmysql+aiomysql://URLs keep working.- Add
IndexColumns(..., case_insensitive=True)to build a case-insensitive unique index (each named column wrapped inLOWER()), so values that differ only in case cannot both be stored.IndexColumnsnow also accepts SQLAlchemy expressions for arbitrary functional indexes. On MySQL this needs 8.0.13+. #615 - Add
flatten_fieldsandflatten_alltoget_pydantic(), matchingmodel_dump()andQuerySet.flatten_fields(). Flattened relations are generated as the related model's pk type (a list of pks for many-to-many and reverse relations) and accept a pk, dict or model, so one generated model works for both requests and responses — thanks @iron3oxide for the initial idea in #893 #1850
⚡ Performance
- Rows of models without custom validators, encrypted or base64 fields are turned into models directly from the already converted column values instead of going through
__init__and validation again (rows holding a related model still go through__init__), queries of such models withoutselect_relatedskip the relation-aware row merging, and models without relations skip relation bookkeeping during initialization. Loading many rows is 1.4–2.2× faster in the orm-benchmarks suite (small filters 1.3–1.5×), the most on wide models. For such models values stored in the database are no longer re-validated on load (e.g. a string longer thanmax_lengthwritten outside ormar loads as is); models with an overwritten pydantic type, value-changingmodel_config(use_enum_values, string transformations,strict) or a custom__init__keep full validation. - Rows of such models holding related models (a foreign key,
select_relatedor a reverse relation) are built the same way, with only the relations registered on both sides, and the cached hash of a new instance no longer goes through__getattr__on its first use. Loading rows with a foreign key is about 1.4× faster, withselect_relatedand reverse relations 1.25–1.35× faster. - The relation fields of a model are mapped by name once per model and shared by every instance instead of being rebuilt for each one, which makes building models 5–12% faster.
- Whether rows can be built directly from their values is decided once per query position instead of once per row, which makes loading many rows of a model without relations about 9% faster.
- Native execution builds each row in one step and runs only the columns that have a result processor through it, instead of checking every column of every row. On asyncpg, where most columns need no processor, building a row of a wide model is about 30% faster.
- JSON columns are serialized and deserialized with orjson by default instead of the standard library
json(json_serializerandjson_deserializerofDatabaseConnectionstill override it), which makes reading rows with JSON columns about 7–17% faster. Stored JSON text is compact and keeps non-ASCII characters unescaped. Values orjson rejects fall back tojson; integers over 64 bits stored in JSON are read back as floats, so passjson_deserializer=json.loadsif you store them. values()andvalues_list()pick the returned columns of each row with labels resolved once per query, and rows whose labels already are the returned names are copied as a whole, which makes them 1.2–1.3× faster on wide models.bulk_create()of such models without relations copies field values instead of callingmodel_dump(), batch parameters are bound by position without per-row expansion, and on asyncpg a bulk insert of one column set runs without an explicit transaction (asyncpg'sexecutemanyis atomic on its own). Bulk inserts are about 1.6× faster on a warm connection pool.- Single statements whose values are all named bind parameters are bound by position too, the driver connection of an established connection is read without a greenlet switch, and signals without receivers return immediately: inserts and updates inside a transaction are about 1.15× faster.
- Writes (
save(),update(),delete(),load(),upsert(),QuerySet.update()/delete(),bulk_create()andbulk_update()) now reuse one statement per write shape and only bind the values, like read queries.bulk_create()runs a single-row insert once per row (executemany) inside one transaction instead of building one multi-row statement per call, which also removes the driver's bound-parameter limit on large batches. In the orm-benchmarks suite on PostgreSQL, inserts are 1.1–4.8× and updates 1.4–2.9× faster, the most on wide models.bulk_create()of models with only a primary key now inserts every row (it inserted a single row before). Context-sensitive SQLAlchemy column defaults (default=callable(context)) see the bound parameters of these statements under generated names. - Read queries (
get(),first(),all(),iterate(),values(),count(),exists()and aggregates) now cache the built SQLAlchemy statement per query shape and only bind the new values on later calls, instead of rebuilding the statement and its cache key every time. Aget()by primary key spends ~40% less CPU (about 7.8k instead of 4.8kget()calls per second with 10 concurrent workers on PostgreSQL); in the orm-benchmarks suiteget()is 1.4–2× and small filters 1.2–1.3× faster. - With
asyncpg,asyncmyandaiosqlite, queries now run directly on the driver connection instead of through SQLAlchemy's async execution layer. SQLAlchemy still builds and compiles statements, converts values with its column types and manages the pool and transactions, so results and raisedsqlalchemy.excexceptions are unchanged. On PostgreSQL this makesget()~1.2× faster,values()/values_list()up to 1.7× faster and the orm-benchmarks suite 1.08–1.18× faster overall. SQLAlchemy engine events andecho=Trueno longer see these statements; passDatabaseConnection(url, native_execution=False)to go back to SQLAlchemy's execution layer.aiopgandaiomysqlare unchanged. SQLAlchemy is now pinned to<2.1, as native execution relies on its compiler internals. - The default connection pool size of
DatabaseConnectionis raised from 5 to - SQLAlchemy closes overflow connections on checkin, so with more than 5 concurrent queries every extra one opened a new database connection; with 10 concurrent
get()calls on PostgreSQL this is 4–6× faster. Passpool_sizetoDatabaseConnectionto size the pool for your concurrency. - Adding an already saved child to a reverse
ForeignKeyrelation withadd()no longer queries the database to check that the child exists first; the check now runs only for unsaved children (e.g. with a preset pk), soadd()of saved children is ~2× faster. select_relatedqueries now build each related model once per query result instead of once per joined row, and reuse it in every row it appears in. Queries over deep or fanned-out relations are 2–14× faster (e.g. 1000 rows joined five levels deep with a many-to-many: 1.24s → 0.09s). #1851- Queries also build one pk-only model per related pk for foreign keys that are not selected, instead of one per row, so e.g. loading 1000 books by 50 authors is 1.8× faster.
- On SQLite the engine now runs in AUTOCOMMIT, like MySQL, instead of switching every pooled connection into AUTOCOMMIT and back, which cost two hops to the driver thread per query. Standalone queries (
get,create,save,delete,count, ...) are 25–45% faster; transactions keep using an explicitBEGIN, so savepoints and rollbacks work as before. Postgres is unchanged and a user-suppliedisolation_levelis respected. #1852
🐛 Fixes
- Fix JSON fields of related models turning into strings. Passing a model with a JSON field to a relation (
Pet(owner=owner),create(owner=owner)) or loading it through a forwardselect_relatedleft its JSON values encoded as strings, also inmodel_dump(); the related model now keeps its decoded values. #1885 - Fix
QuerySet.update()with relation, JSON and bytes values. Foreign keys now accept the related model or a dictionary with its pk besides the pk itself (self-referencing foreign keys rejected even the pk), JSON fields accept a value to dump (a dict or list was rejected, and a JSON string was stored encoded twice and read back as a string), and bytes fields accept strings, likecreate()andsave()do. - Fix
get()afterexclude()returning the last row instead of raisingMultipleMatcheswhen several rows match. A queryset narrowed only byexclude()was treated as unfiltered; code relying onexclude(...).get()returning the last row should add afilter()or usefirst()/last(). #1858 - Fix
bulk_update()writing encrypted fields as plain text. The update now runs as a SQLAlchemy statement, so column types process the values like insave()andupdate(). #1866 - Fix
bulk_update()failing on a nullableuuidfield that isNone. #1854 - Fix encrypted
Enumfields storing a value that could not be read back, they are now saved by member name and decrypted to the enum member #1855 - Fix
get_pydantic()cache being keyed by model class name, so same-named models from different modules could get each other's generated models. - Support pydantic 2.14 (upper bound raised to
<2.15). On 2.14 reverse relation fields were dropped from the cached model schema, so they were missing from FastAPI request/response models and OpenAPI docs. - Fix queries over two relation paths ending in the same relation (e.g.
order.buyer.cityandorder.seller.city): filters,exclude(),order_by(),fields(),exclude_fields(),values()andprefetch_related()could target the wrong table, produce cross joins or load fields of the other path, depending on the order of the calls. Table aliases are now derived from the relation path and stable between queries; internallyAliasManagerandOrmarConfig.alias_managerwere removed. - Fix chained
exclude()calls applying only the last one; an emptyexclude()is now a no-op — thanks @moneebullah25 for the initial implementation in #1826 #1816 - Fix
select_related()crashing when a column alias (name=) on the related model equals the relation name — thanks @moneebullah25 for the fix and tests in #1829 #1827 - Fix
add()on a reverse ForeignKey relation silently not inserting a child that already had a primary key set (auuidpk with a default or an explicit id on a non-autoincrement pk) — thanks @moneebullah25 #1819 - Fix
clear()on a self-referencing many-to-many relation deleting through rows by the wrong column. It now removes only the rows of the side being cleared (e.g.person.friends.clear()no longer touchesperson.friend_of), and the relation is emptied only after the delete succeeds — thanks @moneebullah25 #1820 - Fix
add(),remove()and through model updates on the reverse side of a self-referencing many-to-many relation storing the link in the wrong direction (e.g.member.followers.add(other)addedothertomember.follows). #1836 - Fix querying through a self-referencing many-to-many relation resolving the wrong table alias - e.g.
member.followers.all()/.count()returned every row, and filters,order_by(),values()and defaultorders_byon such relations failed or produced cross joins. #1837 - Fix
add()of an already linked child on a many-to-many relation inserting a duplicate through row (it now updates the existing link with passed through fields, if any), andremove()emptying the in-memory relation before the through rows were deleted.remove()now deletes all matching through rows. #1821 - Raise
QueryDefinitionErrorwhenupdate()ordelete()is called on a queryset filtered or excluded by a related model's field (e.g.filter(category__name="x")), instead of generating an invalid statement that ignores or fails on the missing join — thanks @moneebullah25 #1817 - Fix
bulk_create()losing explicit values (a primary key or a field with aserver_default) when the objects in one call had different sets of values set: the insert now runs once per distinct set of keys, so objects with mixed key sets are not inserted in list order (documented in thebulk_create()docs; split such objects into separate calls if you need that order). #1859
0.26.0
✨ Features
- Add
OrmarConfig(comment=...)to attach a SQLCOMMENT ON TABLEvalue to a model — forwarded to the underlying SQLAlchemyTableand emitted bymetadata.create_all()on dialects that support table comments (PostgreSQL, MySQL; SQLite ignores it). #1240
🐛 Fixes
- Fix an unexpected cartesian product (cross join) when filtering on two foreign keys that reach the same target table through the same relation (e.g.
a_port__switch__nameandz_port__switch__name). The filter now resolves complex join aliases in the same depth-first order as the join builder, and ignores complex aliases left in the globally shared alias manager by earlier queries, so a repeated query is no longer corrupted. #1706 - Require
ormar-utils>=0.2.0, which ships CPython stable-ABI (abi3) wheels. A single wheel now works on Python 3.10+ — including 3.14 and future releases — so installing ormar no longer fails for lack of a matchingormar-utilswheel on a new Python. #1702 - Fix race in
get_or_create(and the m2m / reverse-fk variant) where concurrent callers leakedIntegrityError. #1016 - Fix
update_or_createraisingNoMatchinstead of creating when called with a pk that doesn't exist in the database. - Fix
values()/values_list()leaking columns of related models that were pulled in by a filter (e.g.filter(project__id=...)) or by a bareselect_related()but never named infields(). Such relations - and their through models for m2m - are now excluded from the projected result, matching the columns the caller actually requested. #800 - Fix
values()/values_list()leaking main-model columns whenfields()named only nested fields (e.g.values_list("garage__owner", flatten=True)). The flat projection now drops every column from any model the caller never named - including the parent FK column and any in-between models the path passes through - so
flatten=Truereturns the requested nested value instead of the first leaked main-model column. #1060
0.25.0
⚡ Performance
A broad performance pass across model construction, row hydration, relation resolution, alias lookups, and result merging — combining per-class caching, lazy initialization of relation machinery, and porting the hottest helpers to Rust via the new required ormar-utils dependency. End-to-end speedups vs 0.24.0 range from ~12 % on select_related, through ~30 % on iterate and first, to ~60 - 80 % on initialization of models, and up to x2.5 speedup in getting all.
✨ Features
-
Add
flatten_fields()queryset method andmodel_dump(flatten_fields=...)/model_dump(flatten_all=True)arguments to render related models as their primary key value instead of nested dicts — see docs #1641Python 1 2 3 4 5
cars = await Car.objects.flatten_fields("manufacturer").all() assert cars[0].model_dump() == {"id": 1, "name": "Corolla", "manufacturer": 1} # Note the id 1 and not the nested model car.model_dump(flatten_all=True) car.model_dump(flatten_fields={"manufacturer": ...}) -
Add proxy model inheritance (
OrmarConfig(proxy=True)) — child class shares the parent's table and only adds methods / computed fields / a customqueryset_class— thanks @SepehrBazyar — see docs #760Python 1 2 3 4 5
class User(Human): ormar_config = base_ormar_config.copy(proxy=True) def full_name(self) -> str: return f"{self.first_name} {self.last_name}" -
Add per-table
schema=support onOrmarConfigso models can live in non-default database schemas (PostgreSQL full, MySQL with caveats, SQLite not supported for cross-schema FKs) — thanks @hk3dva — see docs #1493 - Add Python-style indexing and slicing on
QuerySet—Track.objects[:10],Track.objects[-5:],Track.objects[5]— thanks @SepehrBazyar — see docs #765 - Add
nulls_orderingargument to.asc()/.desc()(ormar.NullsOrdering.FIRST/LAST) with MySQL emulation — thanks @SepehrBazyar — see docs #769 - Allow filtering by a foreign-key column directly (
Book.objects.filter(Book.author == 5)or with a model instance) without adding a JOIN — thanks @djalouehz — see docs #854 - Add
through_relation_nullableandthrough_reverse_relation_nullabletoormar.ManyToManyto enforceNOT NULLon the through table's FK columns — thanks @evadev-eva — see docs #852 - Add
last()/last_or_none()onQuerySetand exposefirst_or_none()/last()/last_or_none()onQuerysetProxy— see docs #765 - Forward unrecognized
**kwargsfromormar.ForeignKey/ormar.ManyToManytoBaseField— fixescomment=(and otherBaseFieldkwargs) being silently dropped on relation fields — thanks @booqoffsky #1239
🐛 Fixes
- Clearing a nullable
ForeignKeywithinstance.fk = Nonenow also clears the in-memory relation, so subsequent reads returnNonewithout a reload — originally @amit12297, rebased — see docs #1230 - Drop the unnecessary post-
INSERTpk reload insave(), and raiseModelPersistenceErroron backends that cannot return a generated pk (Oracle MySQL with non-AUTO_INCREMENTserver-default pk) instead of silently assigning the row count toModel.pk— thanks @vnicolaichuk #919 SelectActionaggregate identifiers now go throughsqlalchemy.column()instead of string concatenation #1637- Fix the
mkdocsdeployment workflow #1638
0.24.0
✨ Features
- Add
on_updateoption to fields to customize SQLON UPDATEbehavior - thanks @vvanglro #1273 - Allow overriding auto-generated foreign key constraint names via
fk_nameparameter onormar.ForeignKey, useful when the generated name exceeds the database's identifier length limit - thanks @nikelborm #849 - Forward
autoincrementproperty from ormar field to the underlying SQLAlchemy column, enabling DDL with manually managed integer primary keys - thanks @smuething #674
🐛 Fixes
- Run standalone queries under AUTOCOMMIT isolation to remove the per-query
BEGIN/COMMITround-trip introduced in 0.22.0. Restores (and exceeds) 0.21-era performance on per-row CRUD and single-row reads while keeping explicitdatabase.transaction()and savepoints working.bulk_updateanditerateare internally wrapped in an explicit transaction so their batch-commit and server-side-cursor semantics are preserved #1629 #1635
0.23.1
‼️🚨 High vulnerability fixed – please upgrade ASAP
- In this version of ormar a high severity vulnerability (CVE-2026-27953) in model initialization was patched. The vulnerability allowed injection of
__pk_only__and__excluded__parameters through user-supplied**kwargs(e.g. JSON request bodies). Passing__pk_only__=Truebypassed all Pydantic validation, and__excluded__could nullify arbitrary fields. Thanks @Mistz1 for reporting! - Affected versions:
- All versions prior to
0.23.1
0.23.0
‼️🚨 Critical vulnerability fixed – please upgrade ASAP
- In this version of ormar the critical vulnerability (
CVE-2026-26198) in aggregate functions was patched - thanks @AAtomical for reporting. The vulnerability was caused by the way ormar generated SQL queries for aggregate functions, allowing arbitrary SQL execution through user input. - Affected versions:
0.9.9 - 0.12.20.20.0b1 - 0.22.0 (latest)
✨ Breaking changes
- Drop support for Python 3.9
🐛 Fixes
- Fix selecting data with nested models with json fields #1530
- Fix prefetching JSON list field throwing TypeError - thanks @jannyware-inc #1402
0.22.0
✨ Breaking changes
-
Migration from
databaseslibrary to native async SQLAlchemyVersion 0.22.0 migrates from the
databaseslibrary to native async SQLAlchemy using ormar'sDatabaseConnectionwrapper. This provides better integration with SQLAlchemy's async ecosystem and improved transaction handling and avoid dependency on archiveddatabaseslibrary. -
Import changes
Replace
databasesimport withDatabaseConnectionfrom ormar:Python 1 2 3 4 5 6 7
# ormar < 0.22 import databases database = databases.Database("sqlite:///db.sqlite") # ormar >= 0.22 from ormar import DatabaseConnection database = DatabaseConnection("sqlite+aiosqlite:///db.sqlite") -
Database URLs require async drivers
Database connection strings must now use async-compatible drivers:
- SQLite:
sqlite+aiosqlite://(notsqlite://) - PostgreSQL:
postgresql+asyncpg://(notpostgresql://) - MySQL:
mysql+aiomysql://(notmysql://)
Python 1 2 3 4 5
# ormar < 0.22 database = databases.Database("sqlite:///db.sqlite") # ormar >= 0.22 database = DatabaseConnection("sqlite+aiosqlite:///db.sqlite") - SQLite:
-
Engine parameter removed from OrmarConfig
The
engineparameter is no longer needed inOrmarConfig- it's created internally byDatabaseConnection:Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# ormar < 0.22 import databases import sqlalchemy database = databases.Database("sqlite:///db.sqlite") engine = sqlalchemy.create_engine("sqlite:///db.sqlite") base_ormar_config = ormar.OrmarConfig( database=database, metadata=sqlalchemy.MetaData(), engine=engine, # <- No longer needed ) # ormar >= 0.22 from ormar import DatabaseConnection import sqlalchemy database = DatabaseConnection("sqlite+aiosqlite:///db.sqlite") base_ormar_config = ormar.OrmarConfig( database=database, metadata=sqlalchemy.MetaData(), # engine is created internally ) -
Table creation requires sync engine
When using
metadata.create_all(), you must create a separate sync engine:Python 1 2 3 4 5 6 7 8 9 10 11 12 13
# ormar >= 0.22 import sqlalchemy from ormar import DatabaseConnection DATABASE_URL = "sqlite+aiosqlite:///db.sqlite" database = DatabaseConnection(DATABASE_URL) metadata = sqlalchemy.MetaData() # Create a sync engine for table creation sync_engine = sqlalchemy.create_engine( DATABASE_URL.replace('+aiosqlite', '') ) metadata.create_all(sync_engine)
✨ Features
-
Improved transaction handling
Transactions now use context variables and SQLAlchemy savepoints for better nested transaction support:
Python 1 2 3 4 5 6
# Nested transactions with automatic savepoints async with database.transaction(): await Model1.objects.create(...) async with database.transaction(): # Uses savepoint await Model2.objects.create(...) -
Enhanced testing support
The
force_rollbackparameter for transactions makes testing easier. Like in databasesforce_rollbackcan also be used with DatabaseConnection directly to use one global transaction.Python 1 2 3
async with database.transaction(force_rollback=True): # Your test code - will rollback even on success await Model.objects.create(...)
💬 Other
- Improved pyright support - thanks @MaximSrour - #1491
0.21.0
✨ Breaking changes
- Drop support for Python 3.8
- Remove the possibility to exclude parents' fields in children models (discouraged as bad practice anyway)
- Add support for Sqlalchemy 2.0 and drop for 1.4
💬 Other
- Bump dependencies to newer versions: among others pydantic, databases and fastapi
- Move setuptools to dev dependencies
- Solve vulnerabilities in dependencies
🐛 Fixes
- Fix mutable default argument in translate list to dict - thanks @cadlagtrader #1382
- Fix fastapi docs - thanks @inktrap #1362
- Fix clashing many to many fields names #1407
💬 Other
- Add official support for python 3.12 - thanks @ChristopherMacGown #1395
- Unpin pydantic allowing pydantic versions <2.9.0 - thanks @camillol #1388
0.20.2
🐛 Fixes
- Fix mutable default argument in translate list to dict - thanks @cadlagtrader #1382
- Fix fastapi docs - thanks @inktrap #1362
- Fix clashing many to many fields names #1407
💬 Other
- Add official support for python 3.12 - thanks @ChristopherMacGown #1395
- Unpin pydantic allowing pydantic versions <2.9.0 - thanks @camillol #1388
Release notes
0.20.1
✨ Breaking changes
- Note that this is the first non-beta release of ormar with support for Pydantic v2. Check release notes for 0.20.0 and https://collerek.github.io/ormar/0.20.0b1/migration/
🐛 Fixes
- Fix merging same target models when using
select_relatedwithprefetch_related#906 - Fix saving related with pk only models #812
- Fix adding the same relation multiple times corrupting relation cache #1335
✨ Features
- Allow adding indexed on foreign keys by @cmflynn #1276
💬 Other
- Some docs fixes by @Chaoyingz, thanks!
0.20.0
✨ Breaking changes
-
ormarModel configurationInstead of defining a
Metaclass now each of the ormar models require an ormar_config parameter that is an instance of theOrmarConfigclass. Note that the attribute must be namedormar_configand be an instance of the config class.Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import databases import ormar import sqlalchemy database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() # ormar < 0.20 class Album(ormar.Model): class Meta: database = database metadata = metadata tablename = "albums" id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) favorite: bool = ormar.Boolean(default=False) # ormar >= 0.20 class AlbumV20(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="albums_v20" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) favorite: bool = ormar.Boolean(default=False) -
OrmarConfigapi/ parametersThe
ormar_configexpose the same set of settings asMetaclass used to provide. That means that you can use any of the following parameters initializing the config:Python 1 2 3 4 5 6 7 8 9
metadata: Optional[sqlalchemy.MetaData] database: Optional[databases.Database] engine: Optional[sqlalchemy.engine.Engine] tablename: Optional[str] order_by: Optional[List[str]] abstract: bool queryset_class: Type[QuerySet] extra: Extra constraints: Optional[List[ColumnCollectionConstraint]] -
BaseMetaequivalent - best practiceNote that to reduce the duplication of code and ease of development it's still recommended to create a base config and provide each of the models with a copy. OrmarConfig provides a convenient
copymethod for that purpose.The
copymethod accepts the same parameters asOrmarConfiginit, so you can overwrite if needed, but by default it will return already existing attributes, except for:tablename,order_byandconstraintswhich by default are cleared.Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import databases import ormar import sqlalchemy base_ormar_config = ormar.OrmarConfig( database=databases.Database("sqlite:///db.sqlite"), metadata=sqlalchemy.MetaData() ) class AlbumV20(ormar.Model): ormar_config = base_ormar_config.copy( tablename="albums_v20" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) class TrackV20(ormar.Model): ormar_config = base_ormar_config.copy( tablename="tracks_v20" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) -
choicesField parameter is no longer supported.Before version 0.20 you could provide
choicesparameter to any existing ormar Field to limit the accepted values. This functionality was dropped, and you should useormar.Enumfield that was designed for this purpose. If you want to keep the database field type (i.e. an Integer field) you can always write a custom validator.Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import databases import ormar import sqlalchemy database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() # ormar < 0.20 class Artist(ormar.Model): class Meta: database = database metadata = metadata id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) country: str = ormar.String(default=False, max_length=50, choices=["UK", "US", "Vietnam", "Colombia"]) # ormar >= 0.20 from enum import Enum class Country(str, Enum): UK = "UK" US = "US" VIETNAM = "Vietnam" COLOMBIA = "Colombia" class ArtistV20(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="artists_v20" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) country: Country = ormar.Enum(enum_class=Country) -
pydantic_onlyField parameter is no longer supportedpydantic_onlyfields were already deprecated and are removed in v 0.20. Ormar allows defining pydantic fields as in ordinary pydantic model.Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import databases import ormar import sqlalchemy database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() # ormar < 0.20 class Dish(ormar.Model): class Meta: database = database metadata = metadata tablename = "dishes" id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) cook: str = ormar.String(max_length=40, pydantic_only=True, default="sam") # ormar >= 0.20 class DishV20(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="dishes_v20" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) cook: str = "sam" # this is normal pydantic field -
property_fielddecorator is no longer supportedproperty_fielddecorator was used to provide a way to pass calculated fields that were included in dictionary/ serialized json representation of the model. Version 2.X of pydantic introduced such a possibility, so you should now switch to the one native to the pydantic.Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import databases import ormar import sqlalchemy import pydantic database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() # ormar < 0.20 class Employee(ormar.Model): class Meta: database = database metadata = metadata id: int = ormar.Integer(primary_key=True) first_name: str = ormar.String(max_length=100) last_name: str = ormar.String(max_length=100) @ormar.property_field() def full_name(self) -> str: return f"{self.first_name} {self.last_name}" # ormar >= 0.20 class EmployeeV20(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, ) id: int = ormar.Integer(primary_key=True) first_name: str = ormar.String(max_length=100) last_name: str = ormar.String(max_length=100) @pydantic.computed_field() def full_name(self) -> str: return f"{self.first_name} {self.last_name}" -
Deprecated methods
All methods listed below are deprecated and will be removed in version 0.30 of
ormar.dict()becomes themodel_dump()
Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import databases import ormar import sqlalchemy database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() class Album(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="albums" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) favorite: bool = ormar.Boolean(default=False) album = Album(name="Dark Side of the Moon") # ormar < 0.20 album_dict = album.dict() # ormar >= 0.20 new_album_dict = album.model_dump()Note that parameters remain the same i.e.
include,excludeetc.json()becomes themodel_dump_json()
Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import databases import ormar import sqlalchemy database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() class Album(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="albums" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) favorite: bool = ormar.Boolean(default=False) album = Album(name="Dark Side of the Moon") # ormar < 0.20 album_json= album.json() # ormar >= 0.20 new_album_dict = album.model_dump_json()Note that parameters remain the same i.e.
include,excludeetc.construct()becomes themodel_construct()
Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
import databases import ormar import sqlalchemy database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() class Album(ormar.Model): ormar_config = ormar.OrmarConfig( database=database, metadata=metadata, tablename="albums" ) id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) favorite: bool = ormar.Boolean(default=False) params = { "name": "Dark Side of the Moon", "favorite": True, } # ormar < 0.20 album = Album.construct(**params) # ormar >= 0.20 album = Album.model_construct(**params)To read more about construct please refer to
pydanticdocumentation.
0.12.2
✨ Features
- Bump support for
FastAPIup to the newest version (0.97.0) #1110 - Add support and tests for
Python 3.11#1110
0.12.1
✨ Features
- Massive performance improvements in area of loading the models due to recursive loads and caching of the models and related models. (by @erichaydel - thanks!) #853
💬 Internals
- Benchmarks for comparing performance effect of implemented changes in regard of trends (again, by @erichaydel - thanks!) #853
0.12.0
✨ Breaking Changes
Queryset.bulk_createwill now raiseModelListEmptyErroron empty list of models (by @ponytailer - thanks!) #853
✨ Features
Model.upsert()now handles a flag__force_save__:boolthat allow upserting the models regardless of the fact if they have primary key set or not. Note that setting this flag will cause two queries for each upserted model ->getto check if model exists and laterupdate/insertaccordingly. #889
🐛 Fixes
- Fix for empty relations breaking
constructmethod (by @Abdeldjalil-H - thanks!) #870 - Fix save related not saving models with already set pks (including uuid) #885
- Fix for wrong relations exclusions depending on the order of exclusions #779
- Fix
property_fieldsnot being inherited properly #774
0.11.3
✨ Features
- Document
onupdateandondeletereferential actions inForeignKeyand provideReferentialActionenum to specify the behavior of the relationship (by @SepehrBazyar - thanks!) #724 - Add
CheckColumnto supported constraints in models Meta (by @SepehrBazyar - thanks!) #729
🐛 Fixes
- Fix limiting query result to 0 should return empty list (by @SepehrBazyar - thanks!) #766
💬 Other
0.11.2
🐛 Fixes
- Fix database drivers being required, while they should be optional #713
- Fix boolean field problem in
limitqueries in postgres withoutlimit_raw_sqlflag #704 - Fix enum_class spilling to schema causing errors in OpenAPI #699
0.11.1
🐛 Fixes
- Fix deepcopy issues introduced in pydantic 1.9 #685
0.11.0
✨ Breaking Changes
- Dropped support for python 3.6
Queryset.get_or_createreturns now a tuple with model and bool value indicating if the model was created (by @MojixCoder - thanks!) #554Queryset.count()now counts the number of distinct parent model rows by default, counting all rows is possible by settingdistinct=False(by @erichaydel - thanks) #588
✨ Features
- Added support for python 3.10
🐛 Fixes
- Fix inconsistent
JSONfields behaviour insaveandbulk_create#584 - Fix maximum recursion error #580
0.10.25
✨ Features
- Add
queryset_classoption toModel.Metathat allows you to easily swapQuerySetfor your Model (by @ponytailer - thanks!) #538 - Allow passing extra
kwargstoIndexColumnsthat will be passed to sqlalchemyIndex(by @zevisert - thanks) #575
🐛 Fixes
- Fix nullable setting on
JSONfields #529 - Fix bytes/str mismatch in bulk operations when using orjson instead of json (by @ponytailer - thanks!) #538
0.10.24
✨ Features
- Add
post_bulk_updatesignal (by @ponytailer - thanks!) #524
🐛 Fixes
- Fix support for
pydantic==1.9.0#502 - Fix timezone issues with datetime #504
- Remove literal binds in query generation to unblock postgres arrays #/tophat/ormar-postgres-extensions/9
- Fix bulk update for
JSONfields #519
💬 Other
- Improve performance of
bulk_createby bypassingdatabasesexecute_manysuboptimal implementation. (by @Mng-dev-ai thanks!) #520 - Bump min. required
databasesversion to>=5.4.
0.10.23
✨ Features
- Add ability to pass
commentto sqlalchemy when creating a column #485
🐛 Fixes
- Fix
LargeBinaryfields that can be nullable #409 - Make
ormar.Modelpickable #413 - Make
first()andget()without arguments respect ordering of main model set by user, fallback to primary key (asc, and desc respectively) #453 - Fix improper quoting of non-aliased join
onclauses in postgress #455
0.10.22
🐛 Fixes
- Hot fix for validators not being inherited when parent
ormarmodel was set #365
0.10.21
🐛 Fixes
- Add
ormarimplementation ofconstructclassmethod that allows to buildModelinstances without validating the input to speed up the whole flow, if your data is already validated #318 - Fix for "inheriting" field validators from
ormarmodel when newly created pydanic model is generated withget_pydantic#365
0.10.20
✨ Features
- Add
extraparameter inModel.Metathat acceptsExtra.ignoreandExtra.forbid(default) and either ignores the extra fields passed toormarmodel or raises an exception if one is encountered #358
🐛 Fixes
- Allow
Noneif field is nullable and have choices set #354 - Always set
primary_keytonot nullregardless ofautoincrementand explicitnullablesetting to avoid problems with migrations #348
0.10.19
✨ Features
- Add support for multi-column non-unique
IndexColumnsinMeta.constraints#307 - Add
sql_nullablefield attribute that allows to set different nullable setting for pydantic model and for underlying sql column #308
🐛 Fixes
- Enable caching of relation map to increase performance #337
- Clarify and fix documentation in regard of nullable fields #339
💬 Other
- Bump supported
databasesversion to<=5.2.
0.10.18
🐛 Fixes
0.10.17
✨ Features
- Allow overwriting the default pydantic type for model fields #312
- Add support for
sqlalchemy>=1.4 (requiresdatabases>= 0.5.0) #142
0.10.16
✨ Features
- Allow passing your own pydantic
Configtoormar.Modelthat will be merged with the default one by @naturalethic (thanks!) #285 - Add
SmallIntegerfield type by @ProgrammerPlus1998 (thanks!) #297
🐛 Fixes
- Fix generating openapi schema by removing obsolete pydantic field parameters that were directly exposed in schema #291
- Fix unnecessary warning for auto generated through models #295
0.10.15
🐛 Fixes
- Fix generating pydantic models tree with nested models (by @pawamoy - thanks!) #278
- Fix missing f-string in warning about missing primary key field #274
- Fix passing foreign key value as relation (additional guard, fixed already in the latest release) #270
0.10.14
✨ Features
- Allow passing
timezone:bool = Falseparameter toDateTimeandTimefields for timezone aware database columns #264 - Allow passing datetime, date and time for filter on
DateTime,TimeandDatefields to allow filtering by datetimes instead of converting the value to string #79
🐛 Fixes
- Fix dependencies from
psycopg2topsycopg2-binary#255
0.10.13
✨ Features
- Allow passing field accessors in
select_relatedandprefetch_relatedaka. python styleselect_related#225. - Previously:
Python 1 2
await Post.objects.select_related(["author", "categories"]).get() await Author.objects.prefetch_related("posts__categories").get() - Now also:
Python 1 2
await Post.objects.select_related([Post.author, Post.categories]).get() await Author.objects.prefetch_related(Author.posts.categories).get()
🐛 Fixes
- Fix overwriting default value for inherited primary key #253
0.10.12
🐛 Fixes
- Fix
QuerySet.createmethod not using init (if custom provided) #245 - Fix
ForwardRefManyToManyrelation setting wrong pydantic type #250
0.10.11
✨ Features
- Add
valuesandvalues_listtoQuerySetandQuerysetProxythat allows to return raw data from query #223. - Allow returning list of tuples or list of dictionaries from a query
- Skips parsing the data to ormar model so skips also the validation
- Allow excluding models in between in chain of relations, so you can extract only needed columns
values_listallows you to flatten the result if you extract only one column.
🐛 Fixes
- Fix creation of auto through model for m2m relation with ForwardRef #226
0.10.10
✨ Features
- Add
get_pydanticflag that allows you to auto generate equivalent pydantic models tree from ormar.Model. This newly generated model tree can be used in requests and responses to exclude fields you do not want to include in the data. - Add
exclude_parent_fieldsparameter to model Meta that allows you to exclude fields from parent models during inheritance. Note that best practice is to combine models and mixins but if you have many similar models and just one that differs it might be useful tool to achieve that.
🐛 Fixes
- Fix is null filter with pagination and relations (by @erichaydel) #214
- Fix not saving child object on reverse side of the relation if not saved before #216
💬 Other
- Expand fastapi part of the documentation to show samples of using ormar in requests and responses in fastapi.
- Improve the docs in regard of
default,ForeignKey.addetc.
0.10.9
Important security fix
- Update pin for pydantic to fix security vulnerability CVE-2021-29510
You are advised to update to version of pydantic that was patched. In 0.10.9 ormar excludes versions with vulnerability in pinned dependencies.
🐛 Fixes
- Fix OpenAPi schema for LargeBinary #204
0.10.8
🐛 Fixes
- Fix populating default values in pk_only child models #202
- Fix mypy for LargeBinary fields with base64 str representation #199
- Fix OpenAPI schema format for LargeBinary fields with base64 str representation #199
- Fix OpenAPI choices encoding for LargeBinary fields with base64 str representation
0.10.7
✨ Features
- Add
exclude_primary_keys: bool = Falseflag todict()method that allows to exclude all primary key columns in the resulting dictionaru. #164 - Add
exclude_through_models: bool = Falseflag todict()that allows excluding all through models fromManyToManyrelations #164 - Add
represent_as_base64_str: bool = Falseparameter that allows conversion of bytesLargeBinaryfield to base64 encoded string. String is returned indict(), on access to attribute and string is converted to bytes on setting. Data in database is stored as bytes. #187 - Add
pkalias to allow field access byModel.pkin filters and order by clauses (python style)
🐛 Fixes
- Remove default
Noneoption formax_lengthforLargeBinaryfield #186 - Remove default
Noneoption formax_lengthforStringfield
💬 Other
- Provide a guide and samples of
dict()parameters in the docs - Major refactor of getting/setting attributes from magic methods into descriptors -> noticeable performance improvement
0.10.6
✨ Features
- Add
LargeBinary(max_length)field type #166 -
Add support for normal pydantic fields (including Models) instead of
pydantic_onlyattribute which is now deprecated #160. Pydantic fields should be declared normally as in pydantic model next to ormar fields, note that (obviously)ormardoes not save and load the value for this field in database that mean that ONE of the following has to be true:- pydantic field declared on ormar model has to be
Optional(defaults to None) - pydantic field has to have a default value set
- pydantic field has
default_factoryfunction set - ormar.Model with pydantic field has to overwrite
__init__()and provide the value there
If none of the above
ormar(or rather pydantic) will fail during loading data from the database, with missing required value for declared pydantic field. * Ormar provides now a meaningful examples in openapi schema, including nested models. The same algorithm is used to iterate related models without looks as withdict()andselect/load_all. Examples appear also infastapi. #157 - pydantic field declared on ormar model has to be
🐛 Fixes
- By default
pydanticis not validating fields during assignment, which is not a desirable setting for an ORM, now allormar.Modelshave validation turned-on during assignment (likemodel.column = 'value')
💬 Other
- Add connecting to the database in QuickStart in readme #180
- OpenAPI schema does no longer include
ormar.Modeldocstring as description, instead just model name is provided if you do not provide your own docstring. - Some performance improvements.
0.10.5
🐛 Fixes
- Fix bug in
fastapi-pagination#73 - Remove unnecessary
OptionalinList[Optional[T]]in return value forQuerySet.all()andQuerysetproxy.all()return values #174 - Run tests coverage publish only on internal prs instead of all in github action.
0.10.4
✨ Features
- Add Python style to
filterandorder_bywith field access instead of dunder separated strings. #51 - Accessing a field with attribute access (chain of dot notation) can be used to construct
FilterGroups(ormar.and_andormar.or_) - Field access overloads set of python operators and provide a set of functions to allow same functionality as with dunder separated param names in
**kwargs, that means that querying from sample modelTrackrelated to modelAlbumnow you have more options:- exact - exact match to value, sql
column = <VALUE> - OLD:
album__name__exact='Malibu' - NEW: can be also written as
Track.album.name == 'Malibu - iexact - exact match sql
column = <VALUE>(case insensitive) - OLD:
album__name__iexact='malibu' - NEW: can be also written as
Track.album.name.iexact('malibu') - contains - sql
column LIKE '%<VALUE>%' - OLD:
album__name__contains='Mal' - NEW: can be also written as
Track.album.name % 'Mal') - NEW: can be also written as
Track.album.name.contains('Mal') - icontains - sql
column LIKE '%<VALUE>%'(case insensitive) - OLD:
album__name__icontains='mal' - NEW: can be also written as
Track.album.name.icontains('mal') - in - sql
column IN (<VALUE1>, <VALUE2>, ...) - OLD:
album__name__in=['Malibu', 'Barclay'] - NEW: can be also written as
Track.album.name << ['Malibu', 'Barclay'] - NEW: can be also written as
Track.album.name.in_(['Malibu', 'Barclay']) - isnull - sql
column IS NULL(and sqlcolumn IS NOT NULL) - OLD:
album__name__isnull=True(isnotnullalbum__name__isnull=False) - NEW: can be also written as
Track.album.name >> None - NEW: can be also written as
Track.album.name.isnull(True) - NEW: not null can be also written as
Track.album.name.isnull(False) - NEW: not null can be also written as
~(Track.album.name >> None) - NEW: not null can be also written as
~(Track.album.name.isnull(True)) - gt - sql
column > <VALUE>(greater than) - OLD:
position__gt=3 - NEW: can be also written as
Track.album.name > 3 - gte - sql
column >= <VALUE>(greater or equal than) - OLD:
position__gte=3 - NEW: can be also written as
Track.album.name >= 3 - lt - sql
column < <VALUE>(lower than) - OLD:
position__lt=3 - NEW: can be also written as
Track.album.name < 3 - lte - sql
column <= <VALUE>(lower equal than) - OLD:
position__lte=3 - NEW: can be also written as
Track.album.name <= 3 - startswith - sql
column LIKE '<VALUE>%'(exact start match) - OLD:
album__name__startswith='Mal' - NEW: can be also written as
Track.album.name.startswith('Mal') - istartswith - sql
column LIKE '<VALUE>%'(case insensitive) - OLD:
album__name__istartswith='mal' - NEW: can be also written as
Track.album.name.istartswith('mal') - endswith - sql
column LIKE '%<VALUE>'(exact end match) - OLD:
album__name__endswith='ibu' - NEW: can be also written as
Track.album.name.endswith('ibu') - iendswith - sql
column LIKE '%<VALUE>'(case insensitive) - OLD:
album__name__iendswith='IBU' - NEW: can be also written as
Track.album.name.iendswith('IBU')
- exact - exact match to value, sql
- You can provide
FilterGroupsnot only infilter()andexclude()but also in: get()get_or_none()get_or_create()first()all()delete()- With
FilterGroups(ormar.and_andormar.or_) you can now use: &- asand_instead of next level of nesting|- as `or_' instead of next level of nesting~- as negation of the filter group- To combine groups of filters into one set of conditions use
&(sqlAND) and|(sqlOR)Python 1 2 3 4 5 6 7 8 9 10 11
# Following queries are equivalent: # sql: ( product.name = 'Test' AND product.rating >= 3.0 ) # ormar OPTION 1 - OLD one Product.objects.filter(name='Test', rating__gte=3.0).get() # ormar OPTION 2 - OLD one Product.objects.filter(ormar.and_(name='Test', rating__gte=3.0)).get() # ormar OPTION 3 - NEW one (field access) Product.objects.filter((Product.name == 'Test') & (Product.rating >=3.0)).get() - Same applies to nested complicated filters
Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Following queries are equivalent: # sql: ( product.name = 'Test' AND product.rating >= 3.0 ) # OR (categories.name IN ('Toys', 'Books')) # ormar OPTION 1 - OLD one Product.objects.filter(ormar.or_( ormar.and_(name='Test', rating__gte=3.0), categories__name__in=['Toys', 'Books']) ).get() # ormar OPTION 2 - NEW one (instead of nested or use `|`) Product.objects.filter( ormar.and_(name='Test', rating__gte=3.0) | ormar.and_(categories__name__in=['Toys', 'Books']) ).get() # ormar OPTION 3 - NEW one (field access) Product.objects.filter( ((Product.name='Test') & (Product.rating >= 3.0)) | (Product.categories.name << ['Toys', 'Books']) ).get() - Now you can also use field access to provide OrderActions to
order_by() - Order ascending:
- OLD:
Product.objects.order_by("name").all() - NEW:
Product.objects.order_by(Product.name.asc()).all()
- OLD:
- Order descending:
- OLD:
Product.objects.order_by("-name").all() - NEW:
Product.objects.order_by(Product.name.desc()).all()
- OLD:
- You can of course also combine different models and many order_bys:
Product.objects.order_by([Product.category.name.asc(), Product.name.desc()]).all()
🐛 Fixes
- Not really a bug but rather inconsistency. Providing a filter with nested model i.e.
album__category__name = 'AA'is checking if album and category models are included inselect_related()and if not it's auto-adding them there. The same functionality was not working forFilterGroups(and_andor_), now it works (also for python style filters which returnFilterGroups).
0.10.3
✨ Features
ForeignKeyandManyToManynow supportskip_reverse: bool = Falseflag #118. If you setskip_reverseflag internally the field is still registered on the other side of the relationship so you can:filterby related models fields from reverse modelorder_byby related models fields from reverse model
But you cannot:
* access the related field from reverse model with related_name
* even if you select_related from reverse side of the model the returned models won't be populated in reversed instance (the join is not prevented so you still can filter and order_by)
* the relation won't be populated in dict() and json()
* you cannot pass the nested related objects when populating from dict() or json() (also through fastapi). It will be either ignored or raise error depending on extra setting in pydantic Config.
* Model.save_related() now can save whole data tree in once #148 meaning:
* it knows if it should save main Model or related Model first to preserve the relation
* it saves main Model if
* it's not saved,
* has no pk value
* or save_all=True flag is set
| Text Only | |
|---|---|
1 | |
- it supports also
ManyToManyrelations - it supports also optional
Throughmodel values for m2m relations - Add possibility to customize
Throughmodel relation field names. - By default
Throughmodel relation names default to related model name in lowercase. So in example like this:python ... ## course declaration omitted class Student(ormar.Model): class Meta: database = database metadata = metadata id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) courses = ormar.ManyToMany(Course) ## will produce default Through model like follows (example simplified) class StudentCourse(ormar.Model): class Meta: database = database metadata = metadata tablename = "students_courses" id: int = ormar.Integer(primary_key=True) student = ormar.ForeignKey(Student) ## default name course = ormar.ForeignKey(Course) # default name -
To customize the names of fields/relation in Through model now you can use new parameters to
ManyToMany:through_relation_name- name of the field leading to the model in whichManyToManyis declaredthrough_reverse_relation_name- name of the field leading to the model to whichManyToManyleads to
Example:
Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
... # course declaration omitted class Student(ormar.Model): class Meta: database = database metadata = metadata id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) courses = ormar.ManyToMany(Course, through_relation_name="student_id", through_reverse_relation_name="course_id") # will produce default Through model like follows (example simplified) class StudentCourse(ormar.Model): class Meta: database = database metadata = metadata tablename = "students_courses" id: int = ormar.Integer(primary_key=True) student_id = ormar.ForeignKey(Student) # set by through_relation_name course_id = ormar.ForeignKey(Course) # set by through_reverse_relation_name
🐛 Fixes
- Fix weakref
ReferenceErrorerror #118 - Fix error raised by Through fields when pydantic
Config.extra="forbid"is set - Fix bug with
pydantic.PrivateAttrnot being initialized at__init__#149 - Fix bug with pydantic-type
excludeindict()with__all__key not working
💬 Other
- Introduce link to
sqlalchemy-to-ormarauto-translator for models - Provide links to fastapi ecosystem libraries that support
ormar - Add transactions to docs (supported with
databases)
0.10.2
✨ Features
Model.save_related(follow=False)now accept also two additional arguments:Model.save_related(follow=False, save_all=False, exclude=None).save_all:bool-> By default (so withsave_all=False)ormaronly upserts models that are not saved (so new or updated ones), withsave_all=Trueall related models are saved, regardless ofsavedstatus, which might be useful if updated models comes from api call, so are not changed in the backend.exclude: Union[Set, Dict, None]-> set/dict of relations to exclude from save, those relation won't be saved even withfollow=Trueandsave_all=True. To exclude nested relations pass a nested dictionary like:exclude={"child":{"sub_child": {"exclude_sub_child_realtion"}}}. The allowed values follow thefields/exclude_fields(fromQuerySet) methods schema so when in doubt you can refer to docs in queries -> selecting subset of fields -> fields.Model.update()method now accepts_columns: List[str] = Noneparameter, that accepts list of column names to update. If passed only those columns will be updated in database. Note thatupdate()does not refresh the instance of the Model, so if you change more columns than you pass in_columnslist your Model instance will have different values than the database!Model.model_dump()method previously included only directly related models or nested models if they were not nullable and not virtual, now all related models not previously visited without loops are included indict(). This should be not breaking as just more data will be dumped to dict, but it should not be missing.QuerySet.delete(each=False, **kwargs)previously required that you either pass afilter(by**kwargsor as a separatefilter()call) or seteach=Truenow also acceptsexclude()calls that generates NOT filter. So eithereach=Trueneeds to be set to delete whole table or at least one offilter/excludeclauses.- Same thing applies to
QuerySet.update(each=False, **kwargs)which also previously required that you either pass afilter(by**kwargsor as a separatefilter()call) or seteach=Truenow also acceptsexclude()calls that generates NOT filter. So eithereach=Trueneeds to be set to update whole table or at least one offilter/excludeclauses. - Same thing applies to
QuerysetProxy.update(each=False, **kwargs)which also previously required that you either pass afilter(by**kwargsor as a separatefilter()call) or seteach=Truenow also acceptsexclude()calls that generates NOT filter. So eithereach=Trueneeds to be set to update whole table or at least one offilter/excludeclauses.
🐛 Fixes
- Fix improper relation field resolution in
QuerysetProxyif fk column has different database alias. - Fix hitting recursion error with very complicated models structure with loops when calling
dict(). - Fix bug when two non-relation fields were merged (appended) in query result when they were not relation fields (i.e. JSON)
- Fix bug when during translation to dict from list the same relation name is used in chain but leads to different models
- Fix bug when bulk_create would try to save also
property_fielddecorated methods andpydanticfields - Fix wrong merging of deeply nested chain of reversed relations
💬 Other
- Performance optimizations
- Split tests into packages based on tested area
0.10.1
Features
- add
get_or_none(**kwargs)method toQuerySetandQuerysetProxy. It is exact equivalent ofget(**kwargs)but instead of raisingormar.NoMatchexception if there is no db record matching the criteria,get_or_nonesimply returnsNone.
Fixes
- Fix dialect dependent quoting of column and table names in order_by clauses not working properly in postgres.
0.10.0
Breaking
- Dropped supported for long deprecated notation of field definition in which you use ormar fields as type hints i.e.
test_field: ormar.Integger() = None - Improved type hints ->
mypycan properly resolve related models fields (ForeignKeyandManyToMany) as well as return types ofQuerySetmethods. Those mentioned are now returning proper model (i.e.Book) instead orormar.Modeltype. There is still problem with reverse sides of relation andQuerysetProxymethods, to ease type hints now those returnAny. Partially fixes #112.
Features
- add
select_all(follow: bool = False)method toQuerySetandQuerysetProxy. It is kind of equivalent of the Model'sload_all()method but can be used directly in a query. By defaultselect_all()adds only directly related models, withfollow=Truealso related models of related models are added without loops in relations. Note that it's not and endasyncmodel so you still have to issueget(),all()etc. asselect_all()returns a QuerySet (or proxy) likefields()ororder_by().
Internals
ormarfields are no longer stored as classes inMeta.model_fieldsdictionary but instead they are stored as instances.
0.9.9
Features
- Add possibility to change default ordering of relations and models.
- To change model sorting pass
orders_by = [columns]wherecolumns: List[str]to modelMetaclass - To change relation order_by pass
orders_by = [columns]wherecolumns: List[str] - To change reverse relation order_by pass
related_orders_by = [columns]wherecolumns: List[str] - Arguments can be column names or
-{col_name}to sort descending - In relations you can sort only by directly related model columns or for
ManyToManycolumns alsoThroughmodel columns"{through_field_name}__{column_name}" - Order in which order_by clauses are applied is as follows:
- Explicitly passed
order_by()calls in query - Relation passed
orders_byif exists - Model
Metaclassorders_by - Model primary key column asc (fallback, used if none of above provided)
- To change model sorting pass
- Add 4 new aggregated functions ->
min,max,sumandavgthat are their corresponding sql equivalents.- You can pass one or many column names including related columns.
- As of now each column passed is aggregated separately (so
sum(col1+col2)is not possible, you can havesum(col1, col2)and later add 2 returned sums in python) - You cannot
sumandavgnon numeric columns - If you aggregate on one column, the single value is directly returned as a result
- If you aggregate on multiple columns a dictionary with column: result pairs is returned
- Add 4 new signals ->
pre_relation_add,post_relation_add,pre_relation_removeandpost_relation_remove- The newly added signals are emitted for
ManyToManyrelations (both sides) and reverse side ofForeignKeyrelation (same asQuerysetProxyis exposed). - Signals receive following args:
sender: Type[Model]- sender class,instance: Model- instance to which related model is added,child: Model- model being added,relation_name: str- name of the relation to which child is added, for add signals alsopassed_kwargs: Dict- dict of kwargs passed toadd()
- The newly added signals are emitted for
Changes
Throughmodels for ManyToMany relations are now instantiated on creation, deletion and update, so you can provide not only autoincrement int as a primary key but any column type with default function provided.- Since
Throughmodels are now instantiated you can also subscribe toThroughmodel pre/post save/update/delete signals pre_updatesignals receivers now get also passed_args argument which is a dict of values passed to update function if any (else empty dict)
Fixes
pre_updatesignal now is sent before the extraction of values so you can modify the passed instance in place and modified fields values will be reflected in databasebulk_updatenow works correctly also withUUIDprimary key column type
0.9.8
Features
- Add possibility to encrypt the selected field(s) in the database
- As minimum you need to provide
encrypt_secretandencrypt_backend encrypt_backendcan be one of theormar.EncryptBackendsenum (NONE, FERNET, HASH, CUSTOM) - default:NONE- When custom backend is selected you need to provide your backend class that subclasses
ormar.fields.EncryptBackend - You cannot encrypt
primary_keycolumn and relation columns (FK and M2M). - Provided are 2 backends: HASH and FERNET
- HASH is a one-way hash (like for password), never decrypted on retrieval
- FERNET is a two-way encrypt/decrypt backend
- Note that in FERNET backend you loose
filteringpossibility altogether as part of the encrypted value is a timestamp. - Note that in HASH backend you can filter by full value but filters like
containwill not work as comparison is make on encrypted values - Note that adding
encrypt_backendchanges the database column type toTEXT, which needs to be reflected in db either by migration or manual change
Fixes
- (Advanced/ Internal) Restore custom sqlalchemy types (by
types.TypeDecoratorsubclass) functionality that ceased to working soprocess_result_valuewas never called
0.9.7
Features
- Add
isnulloperator to filter and exclude methods.Python 1 2
album__name__isnull=True #(sql: album.name is null) album__name__isnull=False #(sql: album.name is not null)) - Add
ormar.or_andormar.and_functions that can be used to compose complex queries with nested conditions. Sample query:Check the updated docs in Queries -> Filtering and sorting -> Complex filtersPython 1 2 3 4 5 6 7 8 9 10
books = ( await Book.objects.select_related("author") .filter( ormar.and_( ormar.or_(year__gt=1960, year__lt=1940), author__name="J.R.R. Tolkien", ) ) .all() )
Other
- Setting default on
ForeignKeyorManyToManyraises andModelDefinitionexception as it is (and was) not supported
0.9.6
Important
Throughmodel forManyToManyrelations now becomes optional. It's not a breaking change since if you provide it everything works just fine as it used to. So if you don't want or need any additional fields onThroughmodel you can skip it. Note that it's going to be created for you automatically and still has to be included in example inalembicmigrations. If you want to delete existing one check the default naming convention to adjust your existing database structure.
Note that you still need to provide it if you want to customize the Through model name or the database table name.
Features
- Add
updatemethod toQuerysetProxyso now it's possible to update related models directly from parent model inManyToManyrelations and in reverseForeignKeyrelations. Note that update like inQuerySetupdatereturns number of updated models and does not update related models in place on parent model. To get the refreshed data on parent model you need to refresh the related models (i.e.await model_instance.related.all()) - Add
load_all(follow=False, exclude=None)model method that allows to load current instance of the model with all related models in one call. By default it loads only directly related models but settingfollow=Truecauses traversing the tree (avoiding loops). You can also passexcludeparameter that works the same asQuerySet.exclude_fields()method. - Added possibility to add more fields on
Throughmodel forManyToManyrelationships:- name of the through model field is the lowercase name of the Through class
- you can pass additional fields when calling
add(child, **kwargs)on relation (onQuerysetProxy) - you can pass additional fields when calling
create(**kwargs)on relation (onQuerysetProxy) when one of the keyword arguments should be the through model name with a dict of values - you can order by on through model fields
- you can filter on through model fields
- you can include and exclude fields on through models
- through models are attached only to related models (i.e. if you query from A to B -> only on B)
- note that through models are explicitly loaded without relations -> relation is already populated in ManyToMany field.
- note that just like before you cannot declare the relation fields on through model, they will be populated for you by
ormar, but now if you try to do soModelDefinitionErrorwill be thrown - check the updated ManyToMany relation docs for more information
Other
- Updated docs and api docs
- Refactors and optimisations mainly related to filters, exclusions and order bys
0.9.5
Fixes
- Fix creation of
pydanticFieldInfo after update ofpydanticto version >=1.8 - Pin required dependency versions to avoid such situations in the future
0.9.4
Fixes
- Fix
fastapiOpenAPI schema generation for automatic docs when multiple models refer to the same related one
0.9.3
Fixes
- Fix
JSONfield being double escaped when setting value after initialization - Fix
JSONfield not respectingnullablefield setting due topydanticinternals - Fix
choicesverification forJSONfield - Fix
choicesnot being verified when setting the attribute after initialization - Fix
choicesnot being verified duringupdatecall fromQuerySet
0.9.2
Other
- Updated the Quick Start in docs/readme
- Updated docs with links to queries subpage
- Added badges for code climate and pepy downloads
0.9.1
Features
- Add choices values to
OpenAPIspecs, so it looks like nativeEnumfield in the result schema.
Fixes
- Fix
choicesbehavior withfastapiusage when special fields can be not initialized yet but passed as strings etc.
0.9.0
Important
- Braking Fix: Version 0.8.0 introduced a bug that prevents generation of foreign_keys constraint in the database, both in alembic and during creation through sqlalchemy.engine, this is fixed now.
- THEREFORE IF YOU USE VERSION >=0.8.0 YOU ARE STRONGLY ADVISED TO UPDATE cause despite that most of the
ormarfunctions are working your database CREATED with ormar (or ormar + alembic) does not have relations and suffer from perspective of performance and data integrity. - If you were using
ormarto connect to existing database your performance and integrity should be fine nevertheless you should update to reflect all future schema updates in your models.
Breaking
- Breaking: All foreign_keys and unique constraints now have a name so
alembiccan identify them in db and not depend on db - Breaking: During model construction if
Metaclass of theModeldoes not includemetadataordatabasenowModelDefinitionErrorwill be raised instead of genericAttributeError. - Breaking:
encode/databasesused for running the queries does not have a connection pool for sqlite backend, meaning that each query is run with a new connection and there is no way to enable enforcing ForeignKeys constraints as those are by default turned off on every connection. This is changed inormarsince >=0.9.0 and by default each sqlite3 query has"PRAGMA foreign_keys=1;"run so now each sqlite3 connection by default enforces ForeignKey constraints including cascades.
Other
- Update api docs.
- Add tests for fk creation in db and for cascades in db
0.8.1
Features
- Introduce processing of
ForwardRefin relations. Now you can create self-referencing models - bothForeignKeyandManyToManyrelations.ForwardRefcan be used both fortoandthroughModels. - Introduce the possibility to perform two same relation joins in one query, so to process complex relations like:
Text Only 1 2 3 4 5 6 7
B = X = Y // A \ C = X = Y <= before you could link from X to Y only once in one query unless two different relation were used (two relation fields with different names) - Introduce the
paginatemethod that allows to limit/offset bypageandpage_size. Available forQuerySetandQuerysetProxy.
Other
- Refactoring and performance optimization in queries and joins.
- Add python 3.9 to tests and pypi setup.
- Update API docs and docs -> i.e. split of queries documentation.
0.8.0
Breaking
- Breaking:
remove()parent from child side in reverse ForeignKey relation now requires passing a relationname, as the same model can be registered multiple times andormarneeds to know from which relation on the parent you want to remove the child. - Breaking: applying
limitandoffsetwithselect_relatedis by default applied only on the main table before the join -> meaning that not the total number of rows is limited but just number of main models (first one in the query, the one used to construct it). You can still limit all rows from db response withlimit_raw_sql=Trueflag on eitherlimitoroffset(or both) - Breaking: issuing
first()now fetches the first row ordered by the primary key asc (so first one inserted (can be different for non number primary keys - i.e. alphabetical order of string)) - Breaking: issuing
get()without any filters now fetches the first row ordered by the primary key desc (so should be last one inserted (can be different for non number primary keys - i.e. alphabetical order of string)) - Breaking (internal): sqlalchemy columns kept at
Meta.columnsare no longer bind to table, so you cannot get the column straight from there
Features
- Introduce inheritance. For now two types of inheritance are possible:
- Mixins - don't subclass
ormar.Model, just define fields that are later used on different models (likecreated_dateandupdated_dateon each child model), only actual models create tables, but those fields from mixins are added - Concrete table inheritance - means that parent is marked as
abstract=Truein Meta class and each child has its own table with columns from the parent and own child columns, kind of similar to Mixins but parent also is a (an abstract) Model - To read more check the docs on models -> inheritance section.
- Mixins - don't subclass
- QuerySet
first()can be used withprefetch_related
Fixes
- Fix minor bug in
order_byfor primary model order bys - Fix in
prefetch_queryfor multiple related_names for the same model. - Fix using same
related_nameon different models leading to the same relatedModeloverwriting each other, nowModelDefinitionErroris raised and you need to change the name. - Fix
order_byoverwriting conditions when multiple joins to the same table applied.
Docs
- Split and cleanup in docs:
- Divide models section into subsections
- Divide relations section into subsections
- Divide fields section into subsections
- Add model inheritance section
- Add API (BETA) documentation
0.7.5
- Fix for wrong relation column name in many_to_many relation joins (fix #73)
0.7.4
- Allow multiple relations to the same related model/table.
- Fix for wrong relation column used in many_to_many relation joins (fix #73)
- Fix for wrong relation population for m2m relations when also fk relation present for same model.
- Add check if user provide related_name if there are multiple relations to same table on one model.
- More eager cleaning of the dead weak proxy models.
0.7.3
- Fix for setting fetching related model with UUDI pk, which is a string in raw (fix #71)
0.7.2
- Fix for overwriting related models with pk only in
Model.update() with fields passed as parameters(fix #70)
0.7.1
- Fix for overwriting related models with pk only in
Model.save()(fix #68)
0.7.0
- Breaking: QuerySet
bulk_updatemethod now raisesModelPersistenceErrorfor unsaved models passed instead ofQueryDefinitionError - Breaking: Model initialization with unknown field name now raises
ModelErrorinstead ofKeyError - Added Signals, with pre-defined list signals and decorators:
post_delete,post_save,post_update,pre_delete,pre_save,pre_update - Add
py.typedand modifysetup.pyfor mypy support - Performance optimization
- Updated docs
0.6.2
- Performance optimization
- Fix for bug with
pydantic_onlyfields being required - Add
property_fielddecorator that registers a function as a property that will be included inModel.model_dump()and infastapiresponse - Update docs
0.6.1
- Explicitly set None to excluded nullable fields to avoid pydantic setting a default value (fix #60).
0.6.0
- Breaking: calling instance.load() when the instance row was deleted from db now raises
NoMatchinstead ofValueError - Breaking: calling add and remove on ReverseForeignKey relation now updates the child model in db setting/removing fk column
- Breaking: ReverseForeignKey relation now exposes QuerySetProxy API like ManyToMany relation
- Breaking: querying related models from ManyToMany cleans list of related models loaded on parent model:
- Example:
post.categories.first()will set post.categories to list of 1 related model -> the one returned by first() - Example 2: if post has 4 categories so
len(post.categories) == 4callingpost.categories.limit(2).all()-> will load only 2 children and nowassert len(post.categories) == 2
- Example:
- Added
get_or_create,update_or_create,fields,exclude_fields,exclude,prefetch_relatedandorder_byto QuerySetProxy so now you can use those methods directly from relation - Update docs
0.5.5
- Fix for alembic autogenaration of migration
UUIDcolumns. It should just produce sqlalchemyCHAR(32)orCHAR(36) - In order for this to work you have to set user_module_prefix='sa.' (must be equal to sqlalchemy_module_prefix option (default 'sa.'))
0.5.4
- Allow to pass
uuid_format(allowed 'hex'(default) or 'string') toUUIDfield to change the format in which it's saved. By default field is saved in hex format (trimmed to 32 chars (without dashes)), but you can pass format='string' to use 36 (with dashes) instead to adjust to existing db or other libraries.
Sample: * hex value = c616ab438cce49dbbf4380d109251dce * string value = c616ab43-8cce-49db-bf43-80d109251dce
0.5.3
- Fixed bug in
Model.model_dump()method that was ignoring exclude parameter and not include dictionary argument.
0.5.2
- Added
prefetch_relatedmethod to load subsequent models in separate queries. - Update docs
0.5.1
- Switched to github actions instead of travis
- Update badges in the docs
0.5.0
- Added save status -> you can check if model is saved with
ModelInstance.savedproperty- Model is saved after
save/update/load/upsertmethod on model - Model is saved after
create/get/first/all/get_or_create/update_or_createmethod - Model is saved when passed to
bulk_updateandbulk_create - Model is saved after adding/removing
ManyToManyrelated objects (through model instance auto saved/deleted) - Model is not saved after change of any own field (including pk as
Model.pkalias) - Model is not saved after adding/removing
ForeignKeyrelated object (fk column not saved) - Model is not saved after instantiation with
__init__(w/oQuerySet.createor before callingsave)
- Model is saved after
- Added
Model.upsert(**kwargs)that performssave()if pk not set otherwiseupdate(**kwargs) - Added
Model.save_related(follow=False)that iterates all related objects in all relations and checks if they are saved. If not it callsupsert()on each of them. - Breaking: added raising exceptions if
add-ing/remove-ing not saved (pk is None) models toManyToManyrelation - Allow passing dictionaries and sets to fields and exclude_fields
- Auto translate str and lists to dicts for fields and exclude_fields
- Breaking: passing nested models to fields and exclude_fields is now by related ForeignKey name and not by target model name
- Performance optimizations - in modelproxy, newbasemodel - > less queries, some properties are cached on models
- Cleanup of unused relations code
- Optional performance dependency orjson added (strongly recommended)
- Updated docs
0.4.4
- add exclude_fields() method to exclude fields from sql
- refactor column names setting (aliases)
- fix ordering by for column with aliases
- additional tests for fields and exclude_fields
- update docs
0.4.3
- include properties in models.model_dump() and model.model_dump_json()
0.4.2
- modify creation of pydantic models to allow returning related models with only pk populated
0.4.1
- add order_by method to queryset to allow sorting
- update docs
0.4.0
- Changed notation in Model definition -> now use name = ormar.Field() not name: ormar.Field()
- Note that old notation is still supported but deprecated and will not play nice with static checkers like mypy and pydantic pycharm plugin
- Type hint docs and test
- Use mypy for tests also not, only ormar package
- Fix scale and precision translation with max_digits and decimal_places pydantic Decimal field
- Update docs - add best practices for dependencies
- Refactor metaclass and model_fields to play nice with type hints
- Add mypy and pydantic plugin to docs
- Expand the docs on ManyToMany relation
0.3.11
- Fix setting server_default as default field value in python
0.3.10
- Fix postgresql check to avoid exceptions with drivers not installed if using different backend
0.3.9
- Fix json schema generation as of #19
- Fix for not initialized ManyToMany relations in fastapi copies of ormar.Models
- Update docs in regard of fastapi use
- Add tests to verify fastapi/docs proper generation
0.3.8
- Added possibility to provide alternative database column names with name parameter to all fields.
- Fix bug with selecting related ManyToMany fields with
fields()if they are empty. - Updated documentation
0.3.7
- Publish documentation and update readme
0.3.6
- Add fields() method to limit the selected columns from database - only nullable columns can be excluded.
- Added UniqueColumns and constraints list in model Meta to build unique constraints on list of columns.
- Added UUID field type based on Char(32) column type.
0.3.5
- Added bulk_create and bulk_update for operations on multiple objects.
0.3.4
Add queryset level methods * delete * update * get_or_create * update_or_create
0.3.3
- Add additional filters - startswith and endswith
0.3.2
- Add choices parameter to all fields - limiting the accepted values to ones provided
0.3.1
- Added exclude to filter where not conditions.
- Added tests for mysql and postgres with fixes for postgres.
- Rafactors and cleanup.
0.3.0
- Added ManyToMany field and support for many to many relations