反序列化之跨表

当遇到需要去数据库中查询向前端传值时,需要序列化,但是有些字段需要跨表查询,比如一个章节表下的课时就需要跨表,就可以使用子序列化------第一种方式

第一种方式:子序列化

class CourseSectionSerializer(ModelSerializer):
    class Meta:
        model = CourseSection
        fields = ['id', 'name',
                  'section_type_name',
                  'section_link',
                  'duration',
                  'free_trail', ]


class CourseChapterSerializer(ModelSerializer):
    '''
    拿出章节下所有课时,方案有三种
     -表模型中写
     -序列化类中写
     -方式三子序列化
     '''
    coursesections = CourseSectionSerializer(many=True)  # 章节下的课时,是多条,使用子序列化,instance不用传,但是many=True必须传

    class Meta:   #章节表
        model = CourseChapter  
        fields = ['id', 'name', 'chapter', 'summary', 'coursesections']

保存的一种方法,可以忽略

class PaySerializer(serializers.ModelSerializer):
    # {'subject': '某个课程', 'total_amount':100, 'pay_type': 1, 'courses': [1, 2, 3]}
    # 高级用法 传入的courses=[1,2,3]---->courses=[id为1的课程对象,id为2的课程对象,id为3的课程对象]                                                     #课程表
    courses = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(),
                                                 many=True)

    class Meta:
        model = Order
        fields = ['subject', 'total_amount', 'pay_type', 'courses']

    def _check_moeny(self, attrs):    #查看价格是否一致
        courses = attrs.get('courses')
        total_amount = attrs.get('total_amount')
        mun = 0
        for course in courses:
            meony = course.price
            mun += meony
        if not total_amount == mun:
            raise APIException('价格不一致')

第二种方式:序列化类中定义get_字段

class ProjectDetailModelSerializer(serializers.ModelSerializer):
    """
    ymq
    产品详细序列化
    """
    goods_info = serializers.SerializerMethodField()
    goods_img = serializers.SerializerMethodField()
    pjDataList = serializers.SerializerMethodField()
    is_shoucang = serializers.SerializerMethodField()

    class Meta:
        model = models.Project
        fields = ['id', 'goods_info', 'goods_img', 'pjDataList', 'is_shoucang']

    def get_goods_info(self, obj):
        """
        商品详细
        """
        goods_info = {'goods_id': obj.id, 'goods_title': obj.title, 'goods_price': obj.price,
                      'goods_time': obj.renovation_time, 'goods_diqu': obj.renovation_range,
                      'goods_xiaoliang': obj.sales_volume, 'content': obj.desc}
        return goods_info

    def get_goods_img(self, obj):
        """
        商品轮播图
        """
        """
        goods_img: [
         {'img': 'https://tgi12.jia.com/129/144/29144025.jpg'},
         {'img': 'https://tgi1.jia.com/129/144/29144031.jpg' },
         {'img': 'https://tgi1.jia.com/129/144/29144032.jpg' },
         {'img': 'https://tgi13.jia.com/127/342/27342599.jpg' },
         ]
        """
        pro_img_list = obj.p_p.all()

        return [{'id': item.id, 'img': settings.NEW_BASE_URL + item.image.url} for item in pro_img_list]

    def get_pjDataList(self, obj):
        """
        获取评论
        """
        """
        
        [
     { headpic: 'https://tgi13.jia.com/127/342/27342599.jpg', author: '张三', add_time: '2018-06-01', content:'好评好评,真实太好了!'},
     { headpic: 'https://tgi13.jia.com/127/342/27342599.jpg', author: '张三', add_time: '2018-06-01', content: '好评好评,真实太好了!' }
   ]
        """
        pro_img_list = obj.pc_p.all().filter(depth=1, reply__isnull=True)[:2]
        good_list = [{'headpic': item.userinfo.icon, 'author': item.userinfo.username,
                      'add_time': str(item.create_time).replace('T', ' '),
                      'content': item.comment} for item in pro_img_list]
        # 如果评论为空
        if not good_list:
            good_list = [{'headpic': '', 'author': '', 'add_time': '',
                          'content': '暂无评价!'}]
        return good_list

    def get_is_shoucang(self, obj):
        # print(obj.id)
        # print(self.context['request'].user)
        return models.Shoucang.objects.filter(userinfo_id=self.context['request'].user.id, project_id=obj.id)

你可能感兴趣的:(Django,django)