Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model multiple updates with objects' own data?

I've seen code in the django docs that does multiple object updates like

Entry.objects.filter(pub_date__year=2010).update(comments_on=False)

Is there a way to update multiple objects by updating each object's value? For example, add one to all the articles that a user has read

# so it does something like this?
Entry.objects.filter(user_has_read).update(views+=1)
like image 534
Derek Avatar asked Nov 29 '12 16:11

Derek


1 Answers

Yes, by using F() objects:

from django.db.models import F

Entry.objects.filter(user_has_read).update(views=F('views') + 1)

See updating multiple objects, second to last paragraph.

like image 108
Pavel Anossov Avatar answered Oct 24 '22 05:10

Pavel Anossov