我为课程目录提供以下模型:
CourseInstance
是“课程”的运行,该课程是课程目录中的一个条目。每个课程都有一个所属的Department
的外键。每周一次的课程会存储在CourseInstanceTime
中。下面是简化的模型:
class Department(models.Model):
"""Academic Department"""
name = models.CharField(max_length=30, unique=True)
class Course(models.Model):
"""Courses in the course catalog"""
course_name = models.CharField(max_length=30, unique=True)
department = models.ForeignKey(Department, on_delete=models.PROTECT)
course_number = models.DecimalField(decimal_places=0, max_digits=3, unique=True)
class Meta:
unique_together = (("department", "course_number"),)
class CourseInstance(models.Model):
"""A Scheduled running of a particular coursee"""
start_date = models.DateField(help_text='Course Start Date', verbose_name='Start Date')
end_date = models.DateField(help_text='Course Start Date', verbose_name='Start Date')
course = models.ForeignKey(Course, on_delete=models.deletion.CASCADE)
class CourseInstanceTime(models.Model):
day = models.CharField(max_length=3)
start_time = models.TimeField()
end_time = models.TimeField()
course_instance = models.ForeignKey(CourseInstance, on_delete=models.deletion.CASCADE)
我想创建一个包含部门名称的CourseInstance
视图集。我可以使用SlugField
来添加课程编号,如下所示:
class CourseInstanceSerializer(serializers.ModelSerializer): 当然= serializers.SlugRelatedField( 许多=错误, read_only = False, slug_field ='课程编号', queryset = models.Course.objects.all() )
class Meta:
model = models.Course
fields = (
'id',
#'department',
'course',
'start_date',
'end_date',
)
我不知道该怎么做。
答案 0 :(得分:1)
您可以将source
参数传递给序列化程序字段,因此,例如,如果您想向department_name
添加CourseInstanceSerializer
,则可以通过添加字段{ {1}},或者如果您想获取部门信息,则可以使用department_name = serializers.CharField(source='course.department.name')
。