gpt4 book ai didi

python - 如何过滤数据库表行并更新 Django 中的特定列?

转载 作者:行者123 更新时间:2023-11-28 22:09:41 25 4
gpt4 key购买 nike

我有一个数据库表,我想按 id 过滤它并用我写的 if 条件更新特定对象(列)。但它得到一个错误:attributeError: 'int' 对象没有属性 'save'

models.py

class Forcast(models.Model):
current_complete = models.FloatField(null=True)
optimestic = models.BooleanField(null=True)
probable = models.BooleanField(null=True)
pessimistic = models.BooleanField(null=True)
optimestic_percentage = models.FloatField(null=True)
probable_percentage = models.FloatField(null=True)
pessimistic_percentage = models.FloatField(null=True)
weight = models.FloatField(null=True)




views.py

def update(request, id):
item = Forcast.objects.get(id=id)
if request.method == 'POST':
form = CharacterNoteForm(request.POST, instance=item)
if form.is_valid():
current_complete = Forcast.objects.values('current_complete').get(id=id)
print(current_complete['current_complete'])
weight = Forcast.objects.values('weight').get(id=id)
print(weight)
optimestic = form.cleaned_data['optimestic']
probable = form.cleaned_data['probable']
pessimistic = form.cleaned_data['pessimistic']
if current_complete['current_complete'] == 65.0 and optimestic:
optimestic_percentagex = current_complete['current_complete'] * weight['weight']
if probable or pessimistic:
probable_percentagey = current_complete['current_complete'] * weight['weight']
pessimistic_percentagez = current_complete['current_complete'] * weight['weight']
obj = Forcast.objects.filter(id=id).update(optimestic_percentage=optimestic_percentagex)

我除了可以使用我创建的 if 条件更新 optimestic_percentage。有关更多信息,我正在使用 postgresql

最佳答案

你的代码看起来不错,但是 django 框架是用 python 开发的,这意味着你可以使用 Pythonic 的方式找到问题的解决方案,这样你就可以使用 psycopg2 库连接你的数据库并更新你的数据

import psycopg2

try:
conncetion = psycopg2.connect(user='db_user',
password='***',
host='192.168.0.0',
port='5432',
database='****')
cursor = conncetion.cursor()

query_update = ''' UPDATE forecast_Table SET optimestic_percentage = ''' + optimestic_percentagex + ''' WHERE id= ''' + id + ''' '''
cursor.execute(query_update)
conncetion.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into forecast table")
except (Exception, psycopg2.Error) as error:
print("Failed to insert record into forecast table", error)

关于python - 如何过滤数据库表行并更新 Django 中的特定列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57390458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com