具有帐户表,其中具有project_id,project_name,document_count,account_name。 一个帐户有多个项目。我想收集每个帐户的所有项目数据。
数据库:AWS Aurora 型号:
class Account(BASE):
"""
This class represents Account table
"""
__tablename__ = 'Account'
id = Column(Integer, primary_key=True, autoincrement=True)
project_id = Column(String(255), unique=True)
created_at = Column(DateTime, default=datetime.datetime.now)
updated_at = Column(
DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now
)
account_name = Column(String(255))
document_count= Column(SmallInteger, default=0)
account_id = Column(String(255))
project_name = Column(String(255))
status = Column(String(10))
def __init__(self, data):
self.project_id = data["project_id"]
self.account_name = data["account_name"]
self.document_count= data["document_count"]
self.account_id = data["account_id"]
self.project_name = data["project_name"]
self.status = data["status"]
以前,我必须仅合并每个帐户的项目ID。我曾经关注
table = Account
column_name = project_id
filters = Some condition
columns_to_select = ["account_id", "account_name"]
label = project_ids
以下是该SQLAlchemy代码(工作代码)
data = session.query(
func.group_concat(
getattr(table, column_name)
).label(label),
*[getattr(table, column) for column in columns_to_select]
).filter_by(**filters).group_by(getattr(table, group_by)).all()
以上代码的输出:
[{'project_ids': '8882-4ba7-a86e-016d1d58bbc1', 'account_id': '2389-4ea7-9ff2-94fc15eaa981', 'account_name': 'ABC'}, {'project_ids': 'd081-4956-8604-365d6976a842,cu61-34556-76704-323fs6976a845', 'account_id': '9f7d-460f-9de1-800e457d91ef', 'account_name': 'XYZ'}]
现在,我希望结果中包含“ project_name”和文档数。 我做不到
输入:
table = Account
column_names = project_id, project_name, document_count
filters = Some condition
columns_to_select = ["account_id", "account_name"]
label = collected_data
预期输出:
[
{
'collected_data': [('8882-4ba7-a86e-016d1d58bbc1', "project-001", 23)],
'account_id': '2389-4ea7-9ff2-94fc15eaa981', 'account_name': 'ABC'
},
{
'collected_data': [('d081-4956-8604-365d6976a842, "project-002", 12),
('cu61-34556-76704-323fs6976a845', "project-003", 212)]
'account_id': '9f7d-460f-9de1-800e457d91ef', 'account_name': 'XYZ'}
]
请让我知道任何人都可以帮助我。