【问题标题】:How to increment a value in postgres with an update query (python)如何使用更新查询(python)增加postgres中的值
【发布时间】: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


    【解决方案1】:

    你可以使用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)
    

    【讨论】:

    • 是的!那行得通。感谢您链接到 F() 的文档。所以基本上,看起来'+='不像我最初写的那样工作,因为它试图增加一个对象而不是一个值,而 F() 函数本质上只是拉取'logins'字段的值。 +1 快速回答!
    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2011-01-16
    • 2011-09-09
    • 2022-11-06
    • 2020-06-02
    相关资源
    最近更新 更多