【发布时间】:2023-03-13 22:38:01
【问题描述】:
我想运行一个单行更新查询(使用 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 查询。 - 提前致谢!
【问题讨论】:
标签: python django database postgresql sql-update