如何从数据库中的树型数据结构创建json对象?

2024-09-27 23:18:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的烧瓶型号如下:

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对象:

^{pr2}$

Tags: 对象keyiddbmodel烧瓶columninteger
1条回答
网友
1楼 · 发布于 2024-09-27 23:18:46

我使用一个名为Flask-Restless的库来查询数据库并返回json。它是用来和SQLAlchemy一起工作的。在

如果您不希望与这样的东西集成,那么您可以将SQLAlchemy模型子类化,并在其上运行tu 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(Flask Security的作者)

相关问题 更多 >

    热门问题