我想运行一个将值递增 1 的单行更新查询(使用 Python 和 Postgres)。最有效的方法是什么?我认为理想情况下它会看起来像这样(在我的 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 查询。 - 提前致谢!
最佳答案
您可以使用 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)
关于python - 如何使用更新查询增加 postgres 中的值(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53625275/