我有4个模型,其中之一是其他三个模型之间的关系。序列化器也一样。
但是,当我从API检索数据时,我没有收到所有数据,而只收到了“天”,“订单”和“时间”字段,而不是“老师”,“主题”和“ in_class”字段在ScheduleClassTeacherSubjectSerializer上声明
楷模:
class User(models.Model):
name = models.CharField(max_length=20, unique=True, blank=False, null=False)
class Subject(models.Model):
name = models.CharField(max_length=20, unique=True, blank=False, null=False)
class Class(models.Model):
name = models.CharField(max_length=20, unique=True, blank=False, null=False)
class ClassTeacherSubject(models.Model):
teacher = models.ForeignKey(User,
related_name='classes_subjects',
on_delete=models.CASCADE,
null=False,
blank=False,
)
subject = models.ForeignKey(Subject,
related_name='classes_teachers',
on_delete=models.CASCADE,
null=False,
blank=False,
)
teaches_in = models.ForeignKey(Class,
related_name='teachers_subjects',
on_delete=models.CASCADE,
null=False,
blank=False,
)
class Schedule(models.Model):
MONDAY = 'MONDAY'
TUESDAY = 'TUESDAY'
WEDNESDAY = 'WEDNESDAY'
THURSDAY = 'THURSDAY'
FRIDAY = 'FRIDAY'
DAY_CHOICES = (
(MONDAY, 'Monday'),
(TUESDAY, 'Tuesday'),
(WEDNESDAY, 'Wednesday'),
(THURSDAY, 'Thursday'),
(FRIDAY, 'Friday'),
)
ORDER = (
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, 6),
(7, 7),
(8, 8),
(9, 9),
(10, 10),
)
day = models.CharField(max_length=10,
choices=DAY_CHOICES,
null=False,
blank=False
)
order = models.IntegerField(choices=ORDER,
null=False,
blank=False)
time = models.TimeField(null=True,
blank=True,
)
class_teacher_subject = models.ForeignKey(ClassTeacherSubject,
on_delete=models.CASCADE,
null=False,
blank=False,
)
class Meta:
unique_together = ('day', 'order', 'class_teacher_subject')
序列化器:
class TeacherSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'name',)
class SubjectSerializer(serializers.ModelSerializer):
class Meta:
model = Subject
fields = ('id', 'name',)
class ClassSerializer(serializers.ModelSerializer):
class Meta:
model = Class
fields = ('id',
'name')
class ScheduleClassTeacherSubjectSerializer(serializers.HyperlinkedModelSerializer):
teacher = TeacherSerializer(read_only=True)
subject = SubjectSerializer(read_only=True)
in_class = ClassSerializer(read_only=True)
class Meta:
model = User
fields = ('teacher',
'subject',
'in_class',
)
class ScheduleSerializer(serializers.HyperlinkedModelSerializer):
schedule_class_teacher_subject = ScheduleClassTeacherSubjectSerializer(read_only=True)
class Meta:
model = Schedule
fields = (
'day',
'order',
'time',
'schedule_class_teacher_subject',
)
最佳答案
尝试用schedule_class_teacher_subject
替换ScheduleSerializer
中的class_teacher_subject
。
关于python - Django Rest中的序列化器未返回关系对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47206601/