MattG
MattG

Reputation: 1932

How to update Django query object in a for loop

I know you can update all Django records matching a filter by using:

myQuery = myModel.objects.filter(fieldA = 1, FieldB = 2)
myQuery.update(fieldA = 5, FieldB = 6)

But if I want to iterate through the query results and only update certain values, how can I do this? I have tried:

myQuery = myModel.objects.filter(fieldA = 1, FieldB = 2)
for item in range(myQuery.count())
    if (myQuery[item].fieldC) == 10:
        myQuery[item].update(fieldC = 100)

This returns AttributeError: 'myModel' object has no attribute 'update'

Upvotes: 2

Views: 1169

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

As you found out yourself, a Model object has no .update(..) method. You can .save(..) [Django-doc] the object, and specify what fields to update with the update_fields=… parameter [Django-doc]:

myQuery = myModel.objects.filter(fieldA=1, FieldB=2)
for item in myQuery:
    if item.fieldC == 10:
        item.fieldC = 100
        item.save(update_fields=['fieldC'])

That being said, the above is very inefficient. Since for n objects, it will make a total of at most n+1 queries.

You can simply move the condition to the filter part here:

myModel.objects.filter(fieldA=1, FieldB=2, fieldC=10).update(fieldC=100)

Upvotes: 2

Related Questions