2015-05-21 248 views
2

我使用量瓶中,用以下模型:如何從數據庫中的樹數據結構創建一個json對象?

class NewsCategory(db.Model): 
    __tablename__ = 'news_category' 
    id = db.Column(db.Integer, primary_key=True) 
    title = db.Column(db.String(64)) 
    parent_id = db.Column(db.Integer, db.ForeignKey('news_category.id')) 
    children = db.relationship("NewsCategory") 

,我想從這個模型在導航菜單使用創建一個JSON對象。

我想遞歸解析它,並建立一個分層的JSON對象,它看起來是這樣的:

tree = [{"title": "Node 1", "id": "1"}, 
     {"title": "Folder 2", "id": "2", "folder": "true", "children": [ 
      {"title": "Node 2.1", "id": "3"}, 
      {"title": "Node 2.2", "id": "4"} 
      ]} 
     ] 
+0

請包括你已經嘗試了什麼。它工作嗎? –

回答

3

我使用了一個查詢數據庫,並返回JSON稱爲Flask-Restless庫。它使用SQLAlchemy。

如果你不想集成這樣的東西,你可以繼承你的SQLAlchemy模型,並運行to_json()方法。

class NewsCategory(db.Model, JsonSerializer)

class JsonSerializer(object): 
    """A mixin that can be used to mark a SQLAlchemy model class which 
    implements a :func:`to_json` method. The :func:`to_json` method is used 
    in conjuction with the custom :class:`JSONEncoder` class. By default this 
    mixin will assume all properties of the SQLAlchemy model are to be visible 
    in the JSON output. Extend this class to customize which properties are 
    public, hidden or modified before being being passed to the JSON serializer. 
    """ 

    __json_public__ = None 
    __json_hidden__ = None 
    __json_modifiers__ = None 

    def get_field_names(self): 
     for p in self.__mapper__.iterate_properties: 
      yield p.key 

    def to_json(self): 
     field_names = self.get_field_names() 

     public = self.__json_public__ or field_names 
     hidden = self.__json_hidden__ or [] 
     modifiers = self.__json_modifiers__ or dict() 

     rv = dict() 
     for key in public: 
      rv[key] = getattr(self, key) 
     for key, modifier in modifiers.items(): 
      value = getattr(self, key) 
      rv[key] = modifier(value, self) 
     for key in hidden: 
      rv.pop(key, None) 
     return rv 

信用:Github Overholt project(瓶,安全的作者)

+0

我有和上面相同的用例,所以我嘗試了這種方法,作爲'NewsCategory()。to_json()',但得到了一個空字典,如'{'title':None,'id':None,'parent_id ':無,'children':[]}'......我已經證實數據也在底層表中。我有一種感覺,我對'to_json()'方法的調用是不正確的。 –

+0

@horcle_buzz這個方法是爲了在現有的對象上使用 - 你試圖在空對象上使用它嗎? news_cat = NewsCategory.query.filter_by(name ='Technology')。first() news_cat_json = news_cat.to_json() 希望這有助於澄清。 –

+1

嗨。我實際上使用Marshmallow庫中的嵌套方案解決了我的問題。實施起來非常簡單。是的,該對象確實存在爲SQLAlchemy對象。 –

相關問題