如何使用更新查询(python)在postgres中增加值

时间:2018-12-05 04:39:02

标签: python django database postgresql sql-update

我想运行一个单行更新查询(使用Python和Postgres),将值增加1。最有效的方法是什么?我认为理想的做法是看起来像这样(在我的Django Views.py文件中):

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

但是由于'+ =',该代码给了我SyntaxError: invalid syntax-这很奇怪,因为我认为+ =是合法的python(see here)。当然,在postgres中增加一个比这更有效的方法(有效):

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

我在StackOverflow上找到了类似的解决方案,但是他们的答案给出了SQL查询而不是python查询。-预先感谢!

1 个答案:

答案 0 :(得分:2)

您可以使用F功能。

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()

UserProfile.objects.filter(username=username).update(logins=F('login')+1)