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

标签 python django database postgresql sql-update

我想运行一个将值递增 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/

相关文章:

python - 销毁动态创建的小部件

Python 循环缺少结果

php - 不显示来自数据库和文件的图像

php - MySQL 从键/值对表中选择

python - 当主进程终止时,Celery 启动的进程不会停止

python - 三列A B C,当cumsum小于10时取A*B,然后取A*C

python - 从 django/python 中的日志文件读取后如何保持数据格式化

database - Django "bulk_save"和 "bulk_update"

python - Django Haystack Elasticsearch : order by position of matched term

sql - 对多对一关系的聚合数据建模的有效方法(例如,stackoverflow 问题的投票数)