day72作业

"""
1、新建一个django项目,定义一个Car类,有name字符串属性,color整型选择属性(0:银色,1:黑色,2:红色,3:灰色),price全精度小数类型,image图片文件类型,brand字符串类型

2、基于ModelSerializer类,完成Car资源的单查,群查,单增接口
    序列化:显示车名,车的颜色,车的价格,车的海报,车的品牌
    反序列化:必须提供车名,车的价格,车的品牌(车的匹配需要二次确认re_brand),车的颜色默认为银色(可以提供),车的海报不需要提供(默认为空)
"""
# models.py
class Car(models.Model):
    name = models.CharField(max_length=64)
    COLOR_CHOICES = (
        (0, '银色'),
        (1, '黑色'),
        (2, '白色'),
        (3, '红色'),
    )
    color = models.IntegerField(choices=COLOR_CHOICES, default=0)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    img = models.ImageField(upload_to='img/', default='img/default.jpg')
    brand = models.CharField(max_length=64)

    # 自定义序列化字段
    @property
    def car_color(self):
        return self.get_color_display()
# serializers.py
class CarModelSerializer(serializers.ModelSerializer):
    # 自定义反序列化字段
    re_price = serializers.DecimalField(max_digits=8, decimal_places=2, write_only=True)

    class Meta:
        # 绑定类
        model = models.Car
        # 参与序列化与反序列化的字段
        fields = ['name', 'car_color', 'price', 'img', 'brand', 'color', 're_price']
        extra_kwargs = {
            'img': {
                'read_only': True
            },
            'color': {
                'write_only': True
            }
        }

    # 全局钩子
    def validate(self, attrs):
        price = attrs.get('price')
        re_price = attrs.pop('re_price')
        if not price == re_price:
            raise serializers.ValidationError({'re_price': '价格不一致!'})
        return attrs

# views.py
class CarAPIView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        # 单查
        if pk:
            car_obj = models.Car.objects.filter(pk=pk).first()
            if not car_obj:
                return Response({
                    'status': 1,
                    'msg': 'pk error'
                }, status=400)
            serializer_obj = serializers.CarModelSerializer(car_obj)

            return Response({
                'status': 0,
                'msg': 'ok',
                'results': serializer_obj.data
            })
        # 群查
        car_query = models.Car.objects.all()
        serializer_obj = serializers.CarModelSerializer(car_query, many=True)
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializer_obj.data
        })

    def post(self, request, *args, **kwargs):
        # 单增
        serializer_obj = serializers.CarModelSerializer(data=request.data)
        # 校验不通过会自动将错误信息返回给前端
        serializer_obj.is_valid(raise_exception=True)
        car_obj = serializer_obj.save()

        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.CarModelSerializer(car_obj).data
        })
posted @ 2019-12-26 21:48  SetCreed  阅读(81)  评论(0编辑  收藏