day72做業

day72做業
"""
一、新建一個django項目,定義一個Car類,有name字符串屬性,color整型選擇屬性(0:銀色,1:黑色,2:紅色,3:灰色),price全精度小數類型,image圖片文件類型,brand字符串類型前端

二、基於ModelSerializer類,完成Car資源的單查,羣查,單增接口
序列化:顯示車名,車的顏色,車的價格,車的海報,車的品牌
反序列化:必須提供車名,車的價格,車的品牌(車的匹配須要二次確認re_brand),車的顏色默認爲銀色(能夠提供),車的海報不須要提供(默認爲空)
"""git

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)django

# 自定義序列化字段
@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)post

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)code

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
    })
相關文章
相關標籤/搜索