Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all models at once in Django

Tags:

python

sql

django

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!

like image 829
Byteme Avatar asked Mar 29 '13 20:03

Byteme


1 Answers

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.

like image 95
lprsd Avatar answered Sep 18 '22 05:09

lprsd