当前位置:网站首页 > 更多 > 编程开发 > 正文

[Python] django drf serializers 序列化类树形递归的实现 序列化外键字段列表树

作者:CC下载站 日期:2022-03-01 00:00:00 浏览:69 分类:编程开发


父序列化器:

class ReadDeptSerializer(serializers.ModelSerializer):
  id = serializers.IntergerField()
  children = ChildDeptSerializer(many=True)

  class Meta:
    model = Dept
    exclude = ['company','parent']
    depth = 1

子序列化器

class ChildDeptSerializer(serializers.ModelSerializer):
  children = serializers.SerializerMethodField()

  class Meta:
    model = Dept
    depth = 1
    exclude = ['company']

  def get_children(self,obj):
    if obj.children:
      return childDeptSerializer(obj.children,many=True).data
    return None

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯