Update all models at once in Django
14,086
You can use the F()
expression from django.db.models
to do the same:
Model.objects.all().order_by('some_field').update(position=F(some_field)+1)
which will generate a single SQL query to update all of the column values, so it is efficient to the database too.
Related videos on Youtube
Author by
Byteme
Updated on September 24, 2022Comments
-
Byteme over 1 year
I am trying to update position field for all objects in specific order at once in Django (python).
This is how I've done it now, but the problem is that it makes loads of queries.
servers = frontend_models.Server.objects.all().order_by('-vote_count') i = 1 for server in servers: server.last_rank = i server.save() i += 1
Is there a way to update with
Model.objects.all().order_by('some_field').update(position=some_number_that_changes_for each_object)
Thank you!
-
dani herrera about 11 yearsdjango query api don't has windows functions (I think). You should execute custom sql directly if your RDBMS has this feature.
-
-
Daniel Roseman about 11 yearsThis doesn't answer the OP's question, as F() can only calculate based on the value of a field in the same row, rather than incrementing across rows as he wants.
-
lprsd about 11 yearsFor the specific stated problem, it can be refactored to work on the same row too; no?
-
Byteme about 11 yearsthis could work only if i could use previous row with F(same_field_of_previous_row) + 1
-
Andy about 7 years"Instances of F() act as a reference to a model field within a query. These references can then be used in query filters to compare the values of two different fields on the same model instance." Hence this wouldn't accomplish what the OP needs to do.
-
Skylude about 7 yearsAlso we should have some quotes inside that F('some_field') just to be really explicit.