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!