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

Lan
Lan
2022-03-01 / 0 评论 / 438 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年03月01日,已超过990天没有更新,若内容或图片失效,请留言反馈。

www.lanol.cn
父序列化器:

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
1

评论 (0)

取消