Increment/Decrement Field value

Posted: May 26th, 2010 | Author: | Filed under: Django | Tags: | 3 Comments »

Incrementing or decrementing field values can be done by using the F() function.
UPDATE FIELD = FIELD + 1 WHERE… ?

from django.db.models import F

# views.py ...
offer = Offer.objects.get(...)
# SQL: UPDATE field_to_increment = field_to_increment + 1 ...
offer.field_to_increment = F('field_to_increment') + 1
offer.save()

3 Comments on “Increment/Decrement Field value”

  1. 1 nicolás said at 3:52 pm on December 30th, 2011:

    Short and clear. Great info!

  2. 2 Josir said at 5:44 pm on February 23rd, 2012:

    I just didn’t get it. Why not using just

    offer.field_to_increment = offer.field_to_increment – 1

    ??

  3. 3 Davo said at 2:23 pm on April 5th, 2012:

    Hello Josir, what if during that time somebody else increments the value? You will end up setting a wrong value.


Leave a Reply