djang中的restframework的自关联递归循环嵌套的系列化器使用

安装: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")
上一篇:VUE报错解决方法 Unknown custom element: - did you register the component correctly? Fo


下一篇:Unknown custom element: <el-container> - did you register the component correctly? For recursive co