【问题标题】:SQL-Alchemy aggregation with one-to-one relation具有一对一关系的 SQLAlchemy 聚合
【发布时间】:2014-03-03 13:14:04
【问题描述】:

在用于 Angular 应用程序的简单 Flask REST api 中,我有以下模型:

class User(db.Model, ModelMixin):
  """ attributes with _  are not exposed with public_view """
  __tablename__ = "users"
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(32), unique=True, index=True)
  _company_id = db.Column(db.Integer, db.ForeignKey("companies.id"))

class Company(db.Model, ModelMixin):
  __tablename__ = "companies"
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.Unicode(32))
  _employees = db.relationship("User", backref="company", lazy="dynamic")
  _deal = db.relationship("Deal", backref="company", uselist=False)

class Deal(db.Model, ModelMixin):
  __tablename__ = "deals"
  id = db.Column(db.Integer, primary_key=True)
  active = db.Column(db.Boolean(), default=True)
  _company_id = db.Column(db.Integer, db.ForeignKey("companies.id"))

交易和公司是一对一的关系,而公司和用户是一对多的。我正在尝试定义基本的 CRUD 操作并以这种格式返回:

deals = [
        {
         "id": 1,
         "comment": 'This is comment content',
         "company": {
           "id": 5,
           "name": 'Foo',
           "created_on": '20 Mar 2013',
         },
         "employees": [{
           "id": 7,
           "first_name": 'a',
           "last_name": 'b',
           "email": 'ab@b.com'
         },
         {
           "id": 8,
           "first_name": 'A',
           "last_name": 'B',
           "email": 'A@ghgg.com'
         }]
       },
       {
         "id": 2,
     ....

现在我正在考虑将所有有效交易Deal.query.filter_by(active = True).all() 转换为 dict,添加公司并查询员工并添加它,然后返回 json。

有没有更好的生成方法?使用此解决方案,我需要为每 n 笔交易进行 n 次查询,但我不知道如何在 SQL-Alchemy 中进行操作

【问题讨论】:

  • 如果同一家公司有多个交易,您确定要返回每个交易的公司和员工数据吗?可以接受另一种有线格式吗?
  • 你说得对,我不应该在这里遣返员工。我想我应该只返回交易清单。打开替代解决方案。
  • 我正在研究Flask-Presst,这是一个专门为这类场景(SQLAlchemy + 嵌入)设计的 REST API 库。这是一项正在进行的工作,但也许您会发现它很有用。我最近还向 GitHub 添加了 Angular-Presst,这是一个匹配的 AngularJS 库。 (也在进行中)

标签: python angularjs rest sqlalchemy flask


【解决方案1】:

首先,请阅读Format of requests and responses 文档。 flask-restless的回复格式和你想要的不一样。

如果您要使用flask-restless,目前无法预加载Deal._company._employees(只能加载1 级关系)。在您的情况下,您可以在Company 注册端点,这将同时加载Company._dealCompany._employees

api_manager.create_api(
        Company, collection_name="custom_company",
        results_per_page = -1, # disable pagination completely
   )

然后,做:

rv = c.get('/api/custom_company_api',
        headers={'content-type': 'application/json'},
        )

将返回类似:

{
  "num_results": XXX,
  "objects": [
    {
      "_deal": {
        "_company_id": 1,
        "active": true,
        "id": 1
      },
      "employees": [
        {
          "_company_id": 1,
          "id": 1,
          "username": "User1"
        },
        {
          "_company_id": 1,
          "id": 2,
          "username": "User2"
        }
      ],
      "id": 1,
      "name": "Company1"
    },
    {
...
}

我相信,这就是目前flask-restless 所能做到的。如果您要提供自己的自定义端点,那么您可以在一个 SQL 语句中获取所有数据并自行转换为您想要的格式。 sqlalchemy 查询可能如下所示:

from sqlalchemy.orm import joinedload
qry = (db.session.query(Deal)
        .options(
            joinedload(Deal.company).
            joinedload(Company.employees)
            )
        .filter(Deal.active == True)
        )

但是请注意,这只有在您的 _employees 关系不是 "lazy='dynamic'" 时才有效

【讨论】:

    猜你喜欢
    • 2017-02-06
    • 1970-01-01
    • 2021-11-06
    • 2013-02-23
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2020-11-01
    相关资源
    最近更新 更多