我有3个模型:任务,备注,文档。任务可以有一个/多个备注和/或文档。机型:
tasks = Table("tasks", metadata,
Column("id", Integer, primary_key=True)
update_history = Table("update_history", metadata,
Column("id", Integer, primary_key=True),
Column("remarks", String),
Column("task_id", Integer,ForeignKey("tasks.id")),
documents = Table("documents", metadata,
Column("id", Integer, primary_key=True),
Column("file_name", String),
Column("task_id", Integer, ForeignKey("tasks.id"))
省略其他属性。我正在使用sqlalchemy核心仅如何生成表格备注,特定任务的文档。
我试过了:
tasks1 = tasks.alias()
s = select([tasks.c.description.distinct(),
update_history.c.id.label('updates_id'),
update_history.c.remarks,
documents.c.file_name
]).\
where(
and_(
tasks.c.id == task_id,
update_history.c.task_id == task_id,
documents.c.task_id == task_id
)
).\
select_from(update_history.
join(tasks, update_history.c.task_id == tasks.c.id)).\
select_from(documents.
join(tasks1, documents.c.task_id == tasks1.c.id)
)
为此,我得到多个输出,而不是不同的输出,即对于相同的任务,如果有2个备注,2个文档,我的o / p应该只是1个不同的任务id,具有不同的备注,不同的文档名称。目前我得到:
{
"updates_docs": [
{
"description": "Create journal entries for May 2015",
"file_name": "bower.txt",
"remarks": "remark 1 for task 1",
"updates_id": 1
},
{
"description": "Create journal entries for May 2015",
"file_name": "curl_commands.md",
"remarks": "remark 2 for task 1",
"updates_id": 2
},
{
"description": "Create journal entries for May 2015",
"file_name": "curl_commands.md",
"remarks": "remark 1 for task 1",
"updates_id": 1
},
{
"description": "Create journal entries for May 2015",
"file_name": "bower.txt",
"remarks": "remark 2 for task 1",
"updates_id": 2
}
]
}
这是不可取的。有没有更好的方法正确使用distinct和sqlalchemy核心表达式语言? 使用postgresql 9.1