I need to implement this query using django orm:
update table set field=field+1 where id=id
I don't whant to use this:
o = model.objects.get(id=id)
o.field+=1
o.save()
because it use select and when update, and not thread safe.
How to implement this via orm?
¶ Django allows using SQL subqueries.
To do so, open the Django shell to run the query. You might be wonder how Django ORM makes our queries executed or what the corresponding query of the code we are writing. It is quite simple to get the SQL query, we need to use the str() and pass the queryset object along with query.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
Both the previous answerers have part of the solution: you should use update
in conjunction with F()
:
Model.objects.filter(id=id).update(field=F('field') +1))
Note this does an in-place UPDATE without any need for SELECT at all.
for django
v 2.2 (and maybe 3+) SQL statement compilation function could be:
from django.db.models.sql.subqueries import UpdateQuery
def compile_update_query(query_set, update_kwargs):
query = query_set.query.chain(UpdateQuery)
query.add_update_values(update_kwargs)
return str(query)
where query_set
is MyShinyModel.objects.filter(id=42)
and update_kwargs
is a dictionary of model fields to update
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With