Can I do an integer increment inside object update
method?
I.e. I'm doing:
photo = Photos.objects.get(owner_id=user_id)
photo.total_likes = photo.total_likes + 1
photo.save()
Can I do:
Photos.objects.filter(owner_id=user_id).update(total_likes+=1)
答案 0 :(得分:2)
You can use F
object.
Photos.objects.filter(owner_id=user_id).update(total_likes=F('total_likes')+1)
From the Django docs:
An F() object represents the value of a model field. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.
Also benefits of F
is avoiding the race condition
docs
答案 1 :(得分:2)
You can using F expressions. See the docs
>>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)