1、整理今天所学知识点
2、新建一个django项目,定义一个Car类,有name字符串属性,color整型选择属性(0:银色,1:黑色,2:红色,3:灰色),price全精度小数类型,image图片文件类型,brand字符串类型
3、基于ModelSerializer类,完成Car资源的单查,群查,单增接口
序列化:显示车名,车的颜色,车的价格,车的海报,车的品牌
反序列化:必须提供车名,车的价格,车的品牌(车的匹配需要二次确认re_brand),车的颜色默认为银色(可以提供),车的海报不需要提供(默认为空)
# serializers.py
from rest_framework import exceptions,serializers
from django.conf import settings
from api import models
class CarSerializer(serializers.Serializer):
name = serializers.CharField()
price = serializers.DecimalField(max_digits=8,decimal_places=2)
brand = serializers.CharField()
color = serializers.SerializerMethodField()
def get_color(self,obj):
return obj.get_color_display()
img = serializers.SerializerMethodField()
def get_img(self,obj):
return f"http://127.0.0.1:8000{settings.MEDIA_URL}{str(obj.image)}"
class CarDeSerializer(serializers.Serializer):
name = serializers.CharField()
color = serializers.IntegerField(required=False)
price = serializers.DecimalField(max_digits=8, decimal_places=2,required=True)
img = serializers.ImageField(required=False)
brand = serializers.CharField(required=True)
re_brand = serializers.CharField(required=True)
def validate(self, attrs):
brand = attrs.get('brand')
re_brand = attrs.pop('re_brand')
if brand != re_brand:
raise exceptions.ValidationError('两次品牌不一致')
return attrs
def create(self, validated_data):
return models.Car.objects.create(**validated_data)
# views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models,serializers
class Car(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
car_obj = models.Car.objects.get(pk=pk)
car_ser = serializers.CarSerializer(car_obj)
return Response({
'status':0,
'msg':'ok',
'results':car_ser.data
})
car_query = models.Car.objects.all()
car_list_ser = serializers.CarSerializer(car_query,many=True)
return Response({
'status': 0,
'msg': 'ok',
'results': car_list_ser.data
})
def post(self, request, *args, **kwargs):
if not isinstance(request.data, dict) or request.data == {}:
return Response({
'status': 0,
'msg': '数据异常',
})
car_obj = serializers.CarDeSerializer(data=request.data)
print(car_obj)
if car_obj.is_valid():
return Response({
'status': 0,
'msg':'ok',
'results':serializers.CarSerializer(car_obj).data
})
else:
return Response({
'status': 0,
'msg': 'ok',
'results':car_obj.errors
})
# api.urls.py
from django.conf.urls import url,include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/',include('api.urls')),
url(r'^media/(?P<path>.*)',serve,{"document_root":settings.MEDIA_ROOT})
]