Update data in database
Following methods and functions allow updating existing data in the database.
update(each: bool = False, **kwargs) -> intupdate_returning(each: bool = False, **kwargs) -> list[Model]update_or_create(**kwargs) -> Model-
bulk_update(objects: list[Model], columns: list[str] = None) -> None -
ModelModel.update()methodModel.upsert()methodModel.save_related()method
-
QuerysetProxyQuerysetProxy.update_returning(each: bool = False, **kwargs)methodQuerysetProxy.update_or_create(**kwargs)method
update
update(each: bool = False, **kwargs) -> int
QuerySet level update is used to update multiple records with the same value at once.
You either have to filter the QuerySet first or provide a each=True flag to update
whole table.
If you do not provide this flag or a filter a QueryDefinitionError will be raised.
Return number of rows updated.
Values are validated and converted like in create(): a foreign key accepts the
related model, a dictionary with its pk or the pk itself (None clears it), and a
JSON field accepts a value to dump or a JSON string.
| Python | |
|---|---|
1 | |
Warning
Queryset needs to be filtered before updating to prevent accidental overwrite.
To update whole database table each=True needs to be provided as a safety switch
Filters may follow relations of any kind, the update changes the rows the same filters
select in all() (limit and offset do not apply to updates):
| Python | |
|---|---|
1 2 3 4 | |
Such filters select the matched primary keys in a subquery
(WHERE id IN (SELECT ...)).
Column expressions
A value can be computed by the database from the row's own columns, with a field
accessor (Model.field) or ormar.F("field") combined with +, - and *. The
row is changed in one UPDATE, so concurrent updates are not lost:
| Python | |
|---|---|
1 2 3 4 5 6 7 | |
- The literal goes on the right side (
F("stock") + 1),Noneand booleans are rejected. ANULLcolumn makes the resultNULL. - An expression reads non-relation columns of the updated model, or of models reached through its foreign keys, and cannot set a relation (see below).
- It cannot read a column set by the same
update()(MySQL would read the new value, other databases the old one), including fields withon_update. Reading the column it sets is fine. - The database computes the value, so pydantic validators of the field do not run.
The same expressions update a conflicting row in
create(on_conflict="update", update_values=...),
where ormar.Inserted("field") reads the value the insert tried to write.
Reading related models
An expression can read fields of models reached through foreign keys, also several relations deep:
| Python | |
|---|---|
1 2 3 | |
- The related tables are joined in the
UPDATE(UPDATE ... FROMon PostgreSQL and SQLite 3.33+, a multi-tableUPDATEon MySQL and MariaDB). - Rows with no related row on the path (a
NULLforeign key) are not updated and not counted in the returned number. - Reverse and many to many relations are rejected with
QueryDefinitionError, as they can match many rows; filter on them instead. - An expression reading the updated table through a relation (
F("parent__rank")) reads the values from before the update.
Functions
ormar.Greatest, ormar.Least and ormar.Coalesce take two or more arguments,
at least one of them a field or an expression, and combine with other expressions:
| Python | |
|---|---|
1 2 3 4 5 6 7 8 | |
Greatest/Leastcompile toGREATEST()/LEAST(), on SQLite to the scalarmax()/min().- With a
NULLargument PostgreSQL ignores it, while MySQL and SQLite returnNULL. Wrap nullable fields inCoalescefor the same result everywhere. - Literal arguments are typed like in arithmetic, from the first field or expression
argument and the literal (
Greatest(F("count"), 2.5)compares with a float).
ormar.Random() is a random float from 0 (inclusive) to 1 (exclusive), drawn by
the database for each row:
| Python | |
|---|---|
1 2 3 4 | |
It compiles to random() on PostgreSQL, rand() on MySQL and on SQLite to its
integer random() scaled into the same range. Use it with float or decimal
columns: an integer column rounds the value on PostgreSQL and MySQL, while SQLite
stores the fraction.
update_returning
update_returning(each: bool = False, **kwargs) -> list[Model]
Updates the rows like update() (same filters, each flag, value validation and
column expressions) and returns them as stored after the update, instead of their
number:
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 | |
- The models hold the columns of the model's own table: relations are not loaded,
a foreign key is a related model with only its primary key set, like in
all()withoutselect_related().fields(),select_related()andorder_by()of the queryset do not apply, the rows come back in no particular order. - With no matching row nothing is updated and an empty list is returned.
- Rows not updated because an expression found no related row are not returned.
- No signals are sent, like in
update(). QuerysetProxy.update_returning()(e.g.album.tracks.update_returning(...)) updates the related models in one statement, unlike itsupdate(), which callsupdate()of each model; fields of a through model are not updated, andlimit()/offset()do not apply (like inQuerySet.update()), while the proxy'supdate()respects them.
Backends
PostgreSQL and SQLite (3.35+, the SQLite version Python is built with) run one
UPDATE ... RETURNING.
MySQL and MariaDB have no UPDATE ... RETURNING, so inside the open
transaction, or a new one, three statements run:
SELECT <primary key> ... FOR UPDATE with the same filters, UPDATE ... WHERE
<primary key> IN (...) and a locking select (FOR UPDATE) of the updated rows
by primary key. The rows stay locked until the transaction ends and the locking
read sees their latest committed values (not the snapshot of the open
transaction), so the result is the same as with RETURNING, also when other
transactions changed the same rows.
update_or_create
update_or_create(**kwargs) -> Model
Updates the model, or in case there is no match in database creates a new one.
| Python | |
|---|---|
1 | |
Note
Note that if you want to create a new object you either have to pass pk column value or pk column has to be set as autoincrement
bulk_update
bulk_update(objects: list["Model"], columns: list[str] = None) -> None
Allows to update multiple instance at once.
All Models passed need to have primary key column populated.
You can also select which fields to update by passing columns list as a list of string
names.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 | |
Model methods
Each model instance have a set of methods to save, update or load itself.
update
You can update models by updating your model attributes (fields) and calling update() method.
If you try to update a model without a primary key set a ModelPersistenceError exception will be thrown.
Tip
Read more about update() method in models-update
upsert
It's a proxy to either save() or update(**kwargs) methods of a Model.
If the pk is set the update() method will be called.
Tip
Read more about upsert() method in models-upsert
save_related
Method goes through all relations of the Model on which the method is called,
and calls upsert() method on each model that is not saved.
Tip
Read more about save_related() method in models-save-related
QuerysetProxy methods
When access directly the related ManyToMany field as well as ReverseForeignKey returns the list of related models.
But at the same time it exposes subset of QuerySet API, so you can filter, create, select related etc related models directly from parent model.
update_or_create
Works exactly the same as update_or_create function above but allows you to update or create related objects from other side of the relation.
Tip
To read more about QuerysetProxy visit querysetproxy section