通过共享外键嵌套的序列化器

时间:2019-05-17 19:41:05

标签: python django serialization django-rest-framework

我有三种型号。他们中的两个通过外键连接到他们的“父母”。我需要创建一个序列化器。

这是我的模特。py

class Student(models.Model):
    first_name = models.CharField(max_length = 35, blank=True)
    last_name = models.CharField(max_length = 35, blank=True)


class Grade(models.Model):
    student = models.ForeignKey(
        "Student",
        null = True,
        on_delete = models.PROTECT,
    )
    grade = models.FloatField(null = True)


class Attendance(models.Model):
    student = models.ForeignKey(
        "Student",
        null = True,
        on_delete = models.PROTECT,
    )
    total_exabs = models.IntegerField(null = True)

这是我的serializers.py

class StudentSerializer(serializers.BaseSerializer):
        def to_representation(self, student_obj):            
            return {
                "id": student_obj.pk,
                "first_name": student_obj.first_name,
                "last_name": student_obj.last_name,
            }

class GradeSerializer(serializers.BaseSerializer):
    def to_representation(self, grade_obj):
        return {
            "Grade PK": grade_obj.id,
            "Student": grade_obj.student.id,
            "Grade Value": grade_obj.grade,
        }

class AttendanceSerializer(serializers.BaseSerializer):
    def to_representation(self, attendance_obj):
        return {
            "student": attendance_obj.student.id,
            "total_exabs": attendance_obj.total_exabs,
        }

我该如何创建第四个序列化程序,其出勤率嵌套在年级内?我基本上也需要学生的每个年级也要显示出勤率。

这就是我想要的

{"grade_id": "1",
"grade" : "0.73",
"student_id": "1",
"attendance": {"attendance_id": "1", "total_exabs": "7"}}

感谢您提供的任何帮助! Django的新手,感谢您的耐心等待!

1 个答案:

答案 0 :(得分:0)

您的serializers.py可能是,例如:

class GradeSerializer(serializers.ModelSerializer):

    class Meta:
        model=Grade
        fields=["student", "grade"]


class AttendanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Attendance
        fields = ["id", "total_exabs"]

class StudentSerializer(serializers.ModelSerializer):
    attendance_set = AttendanceSerializer(many=True)

    class Meta:
        model=Student
        fields=["id","first_name", "last_name", "attendance_set"]

然后您可以编写:

>>> JSONRenderer().render(StudentSerializer(Student.objects.first()).data)
... b'{"id":1,"first_name":"st1f","last_name":"st1l","attendance_set":[{"id":1,"total_exabs":4},{"id":2,"total_exabs":5},{"id":3,"total_exabs":43}]}'

更新: 您可能会采用的研究生信息完全相同:

class GradeSerializer(serializers.ModelSerializer):

    class Meta:
        model=Grade
        fields=["id", "grade"]

class StudentSerializer(serializers.ModelSerializer):
    grade_set = GradeSerializer(many=True)
    attendance_set = AttendanceSerializer(many=True)

    class Meta:
        model=Student
        fields=["id","first_name", "last_name", "attendance_set", "grade_set" ]

如果每个学生只有一个年级,则必须在该学生的学生模型中具有ForeignKey,而不是该学生的成绩模型中