在选择所有列时,我能否依靠 keys() 始终以与查询结果相同的顺序返回列名?根据我的输出,它似乎是真的,但我找不到任何保证它的文档。我倾向于认为这是真的,因为虽然字典可能是无序的,但它们应该是一致的。
# Loop through each table in the database where all tables
# are being reflected at once.
for table in Base.metadata.tables.values():
# Select all columns
rows = Session.query(table).all()
# Prepend a header row
rows.insert(0, rows[0].keys())
# Output to file
fh = open(filename, 'wb')
outcsv = unicodecsv.writer(fh)
outcsv.writerows(rows)
fh.close
同样,column_descriptions 似乎也以与值相同的顺序返回名称,但我再次不确定它是否总是正确的。
# Prepend list of column names as the first row
rows.insert(0, [col['name'] for col in Session.query(table).column_descriptions])
任何帮助将不胜感激。谢谢!
请您参考如下方法:
返回的行是 KeyedTuple ;它们在 1 个查询中的顺序由原始选择中列的顺序决定,这将绝对保证顺序与 .keys() 返回的顺序相同,并且每个都相同相同查询结果中的项。
