在SQLAlchemy中连接多个列

2024-04-23 13:39:32 发布

您现在位置:Python中文网/ 问答频道 /正文

Have Account表,其中有project\u id、project\u name、document\u count、Account\u 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"]

以前,我只能concat每个帐户的项目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'}]

现在我想要“项目名称”和结果中的文档计数。 我做不到

输入:

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'}
]

请告诉我有谁能帮我。。你知道吗


Tags: nameselfprojectiddatadatetimestringcount