安装:djangorestframework-recursive
pip install djangorestframework-recursive
模型
class Department(models.Model):
parent = models.ForeignKey(to='self', null=True, blank=True, related_name="children", on_delete=models.CASCADE,
verbose_name="父级")
class Meta:
db_table = "department"
ordering = ["id"]
def get_children(self):
return self.children.filter()
序列化器
from rest_framework_recursive.fields import RecursiveField
class DepartmentSerializer(ModelSerializer):
# 给前端返回字段改名,id字段名改为key
key = serializers.IntegerField(source="id")
# 设置子层级递归查询
children = serializers.ListField(source="get_children", child=RecursiveField())
class Meta:
model = AttackPattern
fields = ("key", "children")