gpt4 book ai didi

python - Django Rest 中的序列化器不返回关系对象

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:14 25 4
gpt4 key购买 nike

我有 4 个模型,其中一个是其他三个之间的关系。序列化器也是如此。

但是当我从 API 检索数据时,我没有收到所有数据,我只收到字段“天”、“订单”和“时间”,而不是“教师”、“主题”和“在 ScheduleClassTeacherSubjectSerializer

上声明的 in_class' 字段

型号:

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',
)

最佳答案

尝试将 ScheduleSerializer 中的 schedule_class_teacher_subject 替换为 class_teacher_subject

关于python - Django Rest 中的序列化器不返回关系对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47206601/

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