我正在使用以下代码:
@app.route('/budget_item/<int:budget_id>/edit', methods=['GET', 'POST'])
def budget_item_edit(budget_id):
budget_item = session.query(Budget).filter_by(id=budget_id).one()
print "Start EDIT sequence"
# Return form data from HTML initial load form
elif request.method == 'POST':
budget_amount_reallocated_total = budget_item.budget_amount_reallocated_total
#ORIGINAL BUDGET
if request.form['transaction_type'] == 'Original Budget':
#amount
if request.form['amount'] == "":
amount = 0
else:
amount = float(str(request.form['amount']))
budget_item = Budget(
#created_date = "",
budget_transaction_type = request.form['transaction_type'],
budget_line = request.form['budget_line'],
amount = amount,
description = request.form['description']
#date_received = request.form['date_received']
)
try:
count = 1
while count < 10000:
count += 1
#budget_line
setattr(budget_item,'budget_line'+str(count),request.form['budget_line'+str(count)])
#amount
setattr(budget_item,'amount'+str(count),float(request.form['amount'+str(count)]))
budget_amount_reallocated_total += float(request.form['amount'+str(count)])
setattr(budget_item, 'budget_amount_reallocated_total', budget_amount_reallocated_total)
#description
setattr(budget_item,'description'+str(count), request.form['description'+str(count)])
#date_received
setattr(budget_item,'date_received'+str(count),request.form['date_received'+str(count)])
session.commit()
except:
session.commit()
return redirect(url_for('budget_master'))
else:
print "I'm done! This is not a post request"
此代码块设置为通过POST请求从HTML传递数据,然后更新Postgres DB中的相应对象。我可以确认从DB&#34; budget_item&#34;中查询的对象由settattr正在更新。在文章的最后,我使用commit()来更新对象;但是,数据库并没有反映出这些变化。为了测试以确保事情顺利进行,我尝试了session.add(budget_item),接着是session.commit()以确保连接到数据库是正常的。这样可行。如何将此budget_item对象更新到数据库中?任何帮助深表感谢。
答案 0 :(得分:0)
budget_item.budget_amount_reallocated_total = budget_amount_reallocated_total
session.add(budget_item)
session.commit()
是正确的方法
答案 1 :(得分:0)
要回答您的问题,要更新数据库中已存在的Budget
,您需要更新从数据库中检索到的budget_item = session.query(Budget).filter_by(id=budget_id).one()
实例,即
budget_item = Budget(...)
不是您新创建的那个:
budget_item
这里第一个Budget
表示数据库中的行,因此这是要更新的行。为此,您可以使用以下代码替换创建第二个budget_item.budget_transaction_type = request.form['transaction_type']
budget_item.budget_line = request.form['budget_line']
budget_item.amount = amount
budget_item.description = request.form['description']
实例的代码:
Budget
完成session.commit()
实例的更新后,您可以调用budget_item
将其刷新到数据库。
正如我对您的问题的评论中所提到的,您似乎正在尝试向Budget
添加大量其他属性,所有这些属性都会被sqlalchemy忽略,除非它们在{{1}之间的映射中定义{1}}实例和Budget
表。