我有模型类别,它可以有父类别(自我引用),所以我可以制作类别的层次结构。
from project import db
class Category(db.Model):
__tablename__ = "categories"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(64), nullable=False)
parent_category_id = db.Column(db.Integer, db.ForeignKey('categories.id'), nullable=True)
child_categories = db.relationship('Category', backref=db.backref('parent', remote_side=[id]), lazy=True)
def __init__(self, name, parent_category_id=None):
self.name = name
self.parent_category_id = parent_category_id
我不知道如何编写序列化程序。这是我的尝试:
from flask_restplus import fields
from project import api
category = api.model('Category', {
'id': fields.Integer(),
'name': fields.String(required=True)
})
category['parent'] = fields.Nested(category)
这会引发错误:
RecursionError: maximum recursion depth exceeded while calling a Python object
那么我该如何正确定义呢?