在用于 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()
转换为字典,添加公司并查询员工并添加它,然后返回json。
是否有更好的生成方法?使用此解决方案,我需要对每 n 笔交易进行 n 次查询,但我不知道如何在 SQL-Alchemy 中执行
最佳答案
首先请阅读Format of requests and responses文档。 flask-reSTLess
的响应格式与您想要的不同。
如果您要使用flask-reSTLess
,目前无法预加载Deal._company._employees
(只能加载1级关系)。在您的情况下,您可以在 Company
注册端点,这将加载 Company._deal
以及 Company._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'"
关于python - 具有一对一关系的 SQLAlchemy 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22147773/