Python 通过关联表查询时如何展平SQLAlchemy结果
我有一个Python 通过关联表查询时如何展平SQLAlchemy结果,python,sqlalchemy,Python,Sqlalchemy,我有一个SampleMessage表,其中每个消息都可以使用SampleTag表中的多个标记进行标记。为此,我使用了一个名为SampleMessageTag的关联表 我试图创建一个查询,以更干净的方式返回数据。当前任何给定的结果如下所示: { ...SampleMessageData tags: [{ // this is from the SampleMessageTag table sample_message_id: 1, t
SampleMessage
表,其中每个消息都可以使用SampleTag
表中的多个标记进行标记。为此,我使用了一个名为SampleMessageTag
的关联表
我试图创建一个查询,以更干净的方式返回数据。当前任何给定的结果如下所示:
{
...SampleMessageData
tags: [{
// this is from the SampleMessageTag table
sample_message_id: 1,
tag_id: 2,
id: 3,
tag: {
// this is from the Tag table
name: 'Blabla',
tag_type: 'industry',
id: 2,
}
}]
}
但是我想把这个结果展平,这样标签就只是一个dict,而不是嵌套在另一个dict中的dict
理想情况下,我希望它看起来像:
{
...SampleMessageData
tags: [{
// only data from from the Tag table
name: 'Blabla',
tag_type: 'industry',
id: 2,
}
}]
}
这是可以通过SqlAlchemy查询实现的,还是必须在返回所有结果后循环执行
以下是我的查询当前的样子:
def get_samples(self, skip, limit, industries, annotated_only, months, origins) -> models.SampleMessage:
results_query = self.db.query(models.SampleMessage
).join(
models.SampleMessageTag
).options(
contains_eager(models.SampleMessage.tags
).joinedload(
models.SampleMessageTag.tag
)
).filter(
models.SampleMessage.active==True,
)
if annotated_only:
results_query = results_query.filter(
models.SampleMessage.annotated==True
)
if industries:
results_query = results_query.filter(models.SampleMessageTag.tag_id.in_(industries))
if origins:
results_query = results_query.filter(models.SampleMessage.origin.in_(origins))
if months:
results_query = results_query.filter(extract('month', models.SampleMessage.first_sent).in_(months))
total_rows = results_query.count()
results = results_query.limit(
limit
).offset(
limit*skip # skip in this case refers to page
).all()
return {
"count": total_rows,
"items": results
}
查看文档,您应该使用
seconday=…
参数配置多对多关系,而不是使用2个一对多关系。在这种情况下,您的查询将更加简单,结果应该与您所要查找的完全一致。看起来他使用的是关联对象,而不是关联表。在这种情况下,如前所述,不鼓励使用辅助!他不是在寻找关联对象吗?显示的示例数据表明关联表中没有其他数据,因此我得出结论,关联对象是不必要的。但这一切都取决于@sup_er_dub。是的,你是对的,这是不必要的。但是当前的数据显示他在SampleMessageTags
中有id
作为附加数据!