其他分享
首页 > 其他分享> > serializers_QuerySet

serializers_QuerySet

作者:互联网

class BookSerializers(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)  # read_only 当前字段只读,前端可以不用传  write_only不给前端返回这个字段,但是前端新增和修改必须传
    标题 = serializers.CharField(max_length=64,source='title')
    price = serializers.DecimalField(max_digits=8, decimal_places=2)
    publish_time = serializers.DateTimeField()
    publish_id = serializers.IntegerField()
    # source 相当于起别名 在source=填真正的字段名
    出版社 = serializers.CharField(source="publish.name")
    # SerializerMethodField的方式,然后下面定义get_字段名的方法,一般用与Queryset对象的数据
    
    publish = serializers.SerializerMethodField(allow_null=True)
    # QuerySet对象直接。的方式是拿不出来的,需要遍历
    authors = serializers.SerializerMethodField()

    def get_publish(self,instance):  # instance就是book对象
        res = PublishSerializers(instance=instance.publish)
        return res.data
    def get_authors(self,instance):
        #两只方式
        author111 = instance.authors
        author = instance.authors.all()
        # lis = []
        dic ={}
        for i in author:
            res = AuthorSerializers(instance=i)
            dic.update({i:res.data})
            # lis.append({'xxx':res.data})#不能用get...
        return dic.values()
        # return lis

 

标签:serializers,get,res,QuerySet,publish,instance,source
来源: https://www.cnblogs.com/dzs894330350/p/16024329.html