Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing values in django database

I want to increment the value in the database without having to perform a hit on the db to find the actual value. Effectively, I would like to do something like this... but this does not work. Any elegant solutions?

P.objects.filter(username='John Smith').update(accvalue+=-50)

THANKS!

like image 397
snakesNbronies Avatar asked Jul 03 '12 17:07

snakesNbronies


1 Answers

Check out Django's F() object.

You can combine it with update() method to update the value based on the previos field value i.e.

>>> from django.db.models import F
>>> P.objects.filter(username="John Smith").update(accvalue=F("accvalue") + 50)

This will use database's native UPDATE method to do what you want to do.

like image 106
bx2 Avatar answered Sep 19 '22 12:09

bx2