Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate update query using django orm

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?

like image 861
Evg Avatar asked Mar 10 '13 07:03

Evg


People also ask

Does Django ORM support subquery?

¶ Django allows using SQL subqueries.

How do I use ORM in Django?

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.

What is QuerySet in Django ORM?

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.


2 Answers

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.

like image 147
Daniel Roseman Avatar answered Sep 21 '22 06:09

Daniel Roseman


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

like image 39
Stamper Avatar answered Sep 24 '22 06:09

Stamper