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.

Share:
14,086

Related videos on Youtube

Byteme
Author by

Byteme

Updated on September 24, 2022

Comments

  • Byteme
    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!

  • Daniel Roseman
    Daniel Roseman about 11 years
    This 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
    lprsd about 11 years
    For the specific stated problem, it can be refactored to work on the same row too; no?
  • Byteme
    Byteme about 11 years
    this could work only if i could use previous row with F(same_field_of_previous_row) + 1
  • Andy
    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
    Skylude about 7 years
    Also we should have some quotes inside that F('some_field') just to be really explicit.