在针对角度应用的简单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次查询,而我不知道如何在SQL-Alchemy中进行操作
答案 0 :(得分:2)
首先,请阅读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"
},
{
...
}
我相信,在这一点上,这就是你所能做的一切。如果您要提供自己的自定义端点,那么您可以在一个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'"