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

标签 python json flask sqlalchemy uinavigationbar

我正在使用以下型号的 flask :

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"}
          ]}
        ]

最佳答案

我使用一个名为 Flask-Restless 的库用于查询数据库并返回json。它专为与 SQLAlchemy 一起使用而设计。

如果您不希望与这样的东西集成,您可以对 SQLAlchemy 模型进行子类化,然后在其上运行 to_json() 方法。

类 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 的作者)

关于python - 如何从数据库中的树数据结构创建json对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30367450/

相关文章:

Android:无法从多维 MongoDB jsonObject 转换为 JSONArray

mysql - 选择MySQL表中JSON类型值的计数

具有 Google 云端硬盘访问权限的 Flask Google 登录

Python:检查Azure队列存储是否存在

python - 无法相应地打印结果并将相同的结果写入 csv 文件

sql - Flask/Sqlalchemy 的初始数据

python - 运行 shutdown 的 Cloud Run Flask API 容器进入休眠循环

python - 删除全为零的字符串 - pandas python

python - 如何在按下按钮时提交对文本文件的更改?

python - Annotation auto-placement (matploylib.pyplot) - 或列表注释