2014-08-28 54 views
0

我有一個相當基本CRUDMixin加載一個to_json方法的關係

class CRUDMixin(object): 
    """ create, read, update and delete methods for SQLAlchemy """ 
    id = db.Column(db.Integer, primary_key=True) 

    @property 
    def columns(self): 
     return [ c.name for c in self.__table__.columns ] 

    def read(self): 
     """ return json of this current model """ 
     return dict([ (c, getattr(self, c)) for c in self.columns ]) 

    # ... 

對於一些像Article類將繼承這一點,它可能與另一個類的關係,就像這樣:

author_id = db.Column(db.Integer, db.ForeignKey('users.id')) 

唯一真正的問題是它不會返回json中的任何用戶詳細信息。理想情況下,JSON應該是這樣的:

{ 
    'id': 1234, 
    'title': 'this is an article', 
    'body': 'Many words go here. Many shall be unread. Roman Proverb.', 
    'author': { 
    'id': 14 
    'name': 'Thor', 
    'joined': October 1st, 1994 
    } 
} 

因爲它是現在,它只是給author_id: 14

我可以通過這種方式檢測列是否爲關係並將其加載爲json?

回答

2

你不得不安裝通過添加類似

author = db.relationship("Author") # I assume that you have an Author model 

然後到JSON您的結果有型動物的方式來處理關係整個關係。

看看這2個反應:

jsonify a SQLAlchemy result set in Flask

How to serialize SqlAlchemy result to JSON?

您還可以看看燒瓶的RESTful其提供的方法/裝飾(marshal_with)元帥的結果嵌套對象(關係)的一個好方法。

http://flask-restful.readthedocs.org/en/latest/fields.html#advanced-nested-field

相關問題