1、通过source属性实现
class StudentsSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
sex =serializers.CharField(source='get_sex_display')
theclass = serializers.CharField(source='stuclass.classon')
role = serializers.CharField(source='get_role_display')
profession = serializers.CharField(source='stuclass.profession.pname')
college = serializers.CharField(source='stuclass.profession.college.collegename')
class ChoiceCourseServerializer(serializers.ModelSerializer):
teacher = serializers.CharField(source='teacher.name')
college = serializers.CharField(source='college.collegename')
semster = serializers.CharField(source='semster.semestername')
is_pass = serializers.CharField(source='get_is_pass_display')
class Meta:
model=models.ChoiceCourse
# fields = ['courseid','coursename','teacher','college','students','semster']
fields="__all__"
2、在模型中写函数,以函数名作为序列化字段,序列化的是函数的返回值
#模型类写法
class ChoiceCourse(models.Model):
courseid = models.CharField(max_length=11,verbose_name='选修课id')
coursename = models.CharField(max_length=20,verbose_name='课程名字')
is_pass = models.IntegerField(choices=((1,'未审批'),(2,'审批通过'),(3,'审批不通过')),default=1)
college = models.ForeignKey(to='College', on_delete=models.CASCADE, verbose_name='学院',null=True,db_constraint=False)
@property
def getis_pass(self):
return self.get_is_pass_display()
@property
def get_collegename(self):
return self.college.collegename
#序列化类写法
class ChoiceCourseServerializer(serializers.ModelSerializer):
class Meta:
model= models.ChoiceCourse
fields=['getis_pass','get_collegename','coursename']
3、子序列化的使用:把一个序列化类的对象赋给另一个序列化类的字段。
class ChoiceCourseShowServerializer(serializers.ModelSerializer):
#把别的序列化的对象作为字段,到时候,就会将该子序列化中的所有字段进行序列化,这个很有用
course = ChoiceCourseServerializer()
username = serializers.CharField(source='student.username')
this_id = serializers.IntegerField(source='id')
class Meta:
model = models.StudentChoiceCourse
fields = ['username','this_id','course']