我遇到了sqlalchemy的问题,其中会话似乎成功提交,但数据没有出现在底层数据库表中。但是,在提交之前和之后打印已提交的项目时,数据会显示。基本上,我要做的是分配一个项目(要更新的行),然后更新数据库中的计算值。
任何提示都表示赞赏!如果下面的代码不是最干净的话,请提前道歉 - 我刚刚开始自学python。
query_od_matrix = session.query(dr.ODMatrix).order_by(dr.ODMatrix.distance)
def generate_bins(qry):
mx = session.query(sa.func.max(dr.ODMatrix.origin_stops_id)).scalar()
# Testing
# print mx
for o in range(1, mx+1): # o=origin, d=destination
query = qry.filter(dr.ODMatrix.origin_stops_id == o)
dest_id = []
dest_dist = []
for row in query:
# Testing
# print row.origin_stops_id, row.destination_stops_id, row.distance
dest_id.append(row.destination_stops_id)
dest_dist.append(row.distance)
# Testing
# print dest_id, dest_dist
no_items = len(dest_id)
for d in range(0, no_items):
# Testing
# print d, dest_id[d], dest_dist[d]
if d == 0: # First item
lower = 0
upper = 0.5 * (float(dest_dist[d]) + float(dest_dist[d+1]))
elif d == no_items-1: # Last item
lower = 0.5 * (float(dest_dist[d]) + float(dest_dist[d-1]))
upper = None
else:
lower = 0.5 * (float(dest_dist[d]) + float(dest_dist[d-1]))
upper = 0.5 * (float(dest_dist[d]) + float(dest_dist[d+1]))
item = dr.ODMatrix(origin_stops_id=o, destination_stops_id=dest_id[d])
# Testing
# print d, dest_id[d], lower, upper
# print dest_id[d], item.destination_stops_id
item.bin_from = lower
item.bin_to = upper
# Testing
# session.dirty
# print item.origin_stops_id, item.destination_stops_id, item.bin_from, item.bin_to
session.commit()
# session.flush()
# Testing
# session.dirty
# print item.origin_stops_id, item.destination_stops_id, item.bin_from, item.bin_to
答案 0 :(得分:1)
您需要在提交之前将项目添加到会话
item = dr.ODMatrix(origin_stops_id=o, destination_stops_id=dest_id[d])
item.bin_from = lower
item.bin_to = upper
session.add(item)
session.commit()