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!

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.