Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用更新查询(python)在postgres中增加值_Python_Django_Database_Postgresql_Sql Update - Fatal编程技术网

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

如何使用更新查询(python)在postgres中增加值,python,django,database,postgresql,sql-update,Python,Django,Database,Postgresql,Sql Update,我想运行一行更新查询(使用Python和Postgres),将值增加1最有效的方法是什么?我认为理想情况下应该是这样(在我的Django Views.py文件中): 但由于“+=”,该代码给了我这个SyntaxError:invalid syntax——这很奇怪,因为我认为+=是合法的python()。当然,有比这更有效的方式来增加postgres的价值(这确实有效): 我在StackOverflow上找到了类似的解决方案,但他们的答案是SQL查询而不是python查询。-提前谢谢 您可以使用用

我想运行一行更新查询(使用Python和Postgres),将值增加1最有效的方法是什么?我认为理想情况下应该是这样(在我的Django Views.py文件中):

但由于“+=”,该代码给了我这个
SyntaxError:invalid syntax
——这很奇怪,因为我认为+=是合法的python()。当然,有比这更有效的方式来增加postgres的价值(这确实有效):

我在StackOverflow上找到了类似的解决方案,但他们的答案是SQL查询而不是python查询。-提前谢谢

您可以使用用户功能

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


对成功了。感谢您链接到F()的文档。所以基本上,它看起来不像我最初写的那样工作,因为它试图增加一个对象而不是一个值,而F()函数本质上只是提取“logins”字段的值+一个快速的回答!
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
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)