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

2022-07-13 20:12:49 浏览数 (1)

父序列化器:

代码语言:javascript复制
class ReadDeptSerializer(serializers.ModelSerializer):
  id = serializers.IntergerField()
  children = ChildDeptSerializer(many=True)

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

子序列化器

代码语言:javascript复制
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

0 人点赞