型号:
class Subject(models.Model):
db = 'default'
subjectName = models.CharField(max_length = 100)
cohortID = models.ForeignKey(Cohort, on_delete=models.CASCADE, related_name='subjects')
teacherID = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='subjects', null=True)
class Cohort(models.Model):
db = 'default'
school_creator = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name='cohorts')
mainTeacherID = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, related_name='mainCohorts')
class_name = models.CharField(max_length = 100)
序列化器:
class SubjectSerializer(serializers.ModelSerializer):
class Meta:
model = models.Subject
fields = ('subjectName', 'teacherID', 'pk',)
这是上面使用序列化程序的响应:
{"subjectName":"Maths","teacherID":2,"pk":4}
我想要:
{"subjectName":"Maths","teacherID":2,"pk":4, "cohortName" : "4 B"}
cohortName应该来自模型Cohort.class_name。 我猜是有可能这样做的,因为Subject是通过ForeignKey Subject.cohortID连接到同类群组的。 我尝试添加一些自定义序列化器:
class SubjectCohortSerializer(serializers.ModelSerializer):
cohortName = serializers.SerializerMethodField(read_only=True)
class Meta:
model = models.Subject
fields = ('subjectName', 'teacherID', 'pk','cohortName')
def get_cohortName(self, subject):
return models.Cohort.objects.get(pk=self.context['request'].cohortID.className)
但是肯定我做错了,而且很难掌握上面的序列化程序中发生的事情。
答案 0 :(得分:1)
将您的 get_cohortName()
方法更改为
class SubjectCohortSerializer(serializers.ModelSerializer):
cohortName = serializers.SerializerMethodField(read_only=True)
class Meta:
model = models.Subject
fields = ('subjectName', 'teacherID', 'pk', 'cohortName')
def get_cohortName(self, subject):
return subject.cohortID.className