1

I'd like to run a one-line update query (using Python and Postgres) that increments a value by 1. Whats the most efficient way to do that? I thought that ideally it would look like this (in my Django Views.py file):

def login_user(request):
    UserProfile.objects.filter(username=username).update(logins += 1)

BUT because of the ' += ', that code gives me this SyntaxError: invalid syntax - which is odd because I thought += was legitimate python (see here). Surely there is a more efficient way to increment a value in postgres than this (which does work):

def login_user(request):
    thing = UserProfile.objects.filter(username=username).values("logins")   # gets the initial value
    total_logins = int(thing[0]['logins'])+1   # adds 1 to that value
    UserProfile.objects.filter(username=username).update(logins = total_logins)   # Updates the value in the database

I have found similar solutions on StackOverflow but their answers gave SQL queries instead of python queries. - Thanks in advance!

Michael Romrell
  • 1,026
  • 5
  • 15
  • 31

1 Answers1

2

You can user F function.

def login_user(request):
    thing = UserProfile.objects.get(username=username)  # gets the initial value
    thing.login = F('login') + 1   # adds 1 to that value
    thing.save()

or

UserProfile.objects.filter(username=username).update(logins=F('login')+1)
a_k_v
  • 1,558
  • 7
  • 18
  • 1
    Yes! That worked. Thanks for linking to the docs for F(). So basically, it looks like ' += ' does not work as I originally wrote it because it's trying to increment an Object instead of a Value, whereas the F() function essentially, just pulls the value of the 'logins' field. +1 for a speedy answer! – Michael Romrell Dec 05 '18 at 05:12