从Django模型序列化器

时间:2018-08-06 09:55:00

标签: django django-models django-rest-framework django-serializer

我有三个桌子。学生,学校,成绩

class Student(models.Model):
     name = models.CharField(max_length=225)
     address = models.CharField(max_length=255)
     school = models.Foreignkey(School)  

class School(models.Model):
     name = models.CharField(max_length=225)

class Result(models.Model):
    student = models.Foreignkey(Student)
    marks = models.FloatField()

与这些模型相对应的序列化器就像

class SchoolSerializer(serializers.ModelSerializer):
      class Meta:
           model = School
           fields = '__all__'

class StudentSerializer(serializers.ModelSerializer):
      school = SchoolSerializer(read_only=True)
      class Meta:
            model =  student
            fields = '__all__'

class ResultSerializer(serializers.ModelSerializer):
      student = StudentSerializer(read_only=True)
      class Meta:
           model = student
           fields = '__all__'

每当结果生成器调用时,我希望StudentSerializer应该隐藏学生地址信息。我已经尝试将排除字段添加为

exclude = ('student__address',)
documentation中的

,但这不起作用,因为student__address不是结果模型的模型字段。如何排除该地址字段或在序列化程序响应中隐藏它。

1 个答案:

答案 0 :(得分:1)

您可以定义新的ResultStudentSerializer序列化器,该序列化器仅在ResultSerializer中使用:

class ResultStudentSerializer(serializers.ModelSerializer):
      school = SchoolSerializer(read_only=True)
      class Meta:
            model =  student
            fields = '__all__'
            exclude = ('address',)

class ResultSerializer(serializers.ModelSerializer):
      student = ResultStudentSerializer(read_only=True)
      class Meta:
           model = Result
           fields = '__all__'