我正在尝试将sqlalchemy对象转换为列表列表:
我尝试过:
lambda q: [location.name for obj in q.all()]
并且有效。
但是当我想在列表中添加/追加另一个时,它会中断:
lambda q: [(location.name, obj.name for obj, location in q.all()]
这就是我想要的:
lambda q: [
[location.name, str(obj.flowrate)]
for obj, location in q.all()]
预期产出:
[
['location name','10.0'],
['another location','20.15']
]
更新
qry = db.Session.query(db.Log, db.Location).\
filter(db.Log.location_id == db.Location.id).\
filter(db.Log.location_id == id)
helpers.write_csv_from_query(resp, qry, falcon.HTTP_200, header,
lambda q: [
[location.name, str(obj.flowrate)]
for obj,location in q.all()])
处理对象查询的函数:
def write_csv_from_query(resp, query, status, header, result_func):
"""Writes CSV response."""
csv_name = date_to_str(datetime.now()) + ".csv"
csv_header = ','.join(header) + "\n"
# csv_data = convert_to_csv(result_func(query))
csv_data = []
csv_data = result_func(query)
csv_data = ','.join(csv_data)
resp.status = status
resp.content_type = 'text/csv'
resp.set_header('Content-disposition', 'attachment; filename=' + csv_name)
resp.body = csv_header + csv_data
答案 0 :(得分:1)
由于在第一个示例中,location
与lambda分开(您的迭代变量称为obj
,我认为location
是一些外部变量(q
外部)和你的lambda),你应该只做
lambda q: [(location.name, obj.name for obj in q.all()]
或者你的最后一个例子:
lambda q: [[location.name, str(obj.flowrate)] for obj in q.all()]
或者,因为obj.name
似乎等同于location.name
(这是来自链接要点中已注释掉的部分):
lambda q: [[obj.name, str(obj.flowrate)] for obj in q.all()]
或甚至(如果是链接表):
lambda q: [[obj.location.name, str(obj.flowrate)] for obj in q.all()]
(我无法从你给出的内容中确切地说出正确的表述,但我想这是其中之一。)
摘要:仅迭代一(1)个对象,并从该单个对象中提取信息。