【发布时间】: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