Django rest framwork 序列化时外键关系的处理

转自 https://www.cnblogs.com/liuguniang/p/8087272.html
序列化时外键关系的处理:

第一种:

class KidsSerializer(serializers.ModelSerializer):

class Meta:
    model = Kids
    fields = '__all__'

访问时默认显示外键id ,创建时传id

第二种:

class KidsSerializer(serializers.ModelSerializer):

class Meta:
    model = Kids
    fields = '__all__'
    depth = 1

访问时显示外键字段的所有信息,但是只读的,不可编辑,即新建时不能传值

第三种:

class KidsSerializer(serializers.ModelSerializer):
grade = serializers.SlugRelatedField(queryset=Grade.objects.all(), slug_field='id')

class Meta:
    model = Kids
    fields = '__all__'

访问时显示id/其他,新建时传id值/其他值

class GradeFinanceSerializer(serializers.Serializer):
id = serializers.IntegerField(required=True)
name = serializers.CharField(read_only=True)

class FinancePlanSerializer(serializers.ModelSerializer):
grades = GradeFinanceSerializer(many=True)

访问时只显示定制的字段 新建时以列表形式传值

字段类型在数据库中为枚举的字段显示问题: get_XXX_display

level = serializers.CharField(source='get_level_display')

添加get传参的方法和过滤出想要显示的数据

def get_queryset(self):
name = self.request.query_params.get('name', '')
if name != '':
return Group.objects.filter(name__icontains=name)
else:
return Group.objects.all()

你可能感兴趣的:(Django rest framwork 序列化时外键关系的处理)