序列化字段的跨表查,choice字段显示中文,

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']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值