gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:05 24 4
gpt4 key购买 nike

我有三个模型。其中两个通过外键连接到它们的“父级”。我需要创建一个序列化器。

这是我的 models.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)

这是我的序列化器.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,感谢您的耐心等待!

最佳答案

您的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" ]

如果每个学生只有一个成绩,则您必须在该成绩的学生模型中拥有外键,而不是在该学生的成绩模型中

关于python - 通过共享外键嵌套序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56192636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com