[Django]-Update all models at once in Django

18👍

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.

👤lprsd

0👍

As far as I know, Django’s object-relational mapping system doesn’t provide a way to express this update operation. But if you know how to express it in SQL, then you can run it via a custom SQL query:

from django.db import connection
cursor = connection.cursor()
cursor.execute('''UPDATE myapp_server ...''')

Different database engines express this operation in different ways. In MySQL you’d run this query:

SET @rownum=0;
UPDATE myapp_server A,
       (SELECT id, @rownum := @rownum + 1 AS rank
        FROM myapp_server
        ORDER BY vote_count DESCENDING) B
SET A.rank = B.rank
WHERE A.id = B.id

In PostgreSQL I think you’d use

UPDATE myapp_server A,
       (SELECT id, rownumber() AS rank
        OVER (ORDER BY vote_count DESCENDING)
        FROM myapp_server) B
SET A.rank = B.rank
WHERE A.id = B.id

(but that’s untested, so beware!).

Leave a comment