1、新建一个django项目,定义一个Car类,有name字符串属性,color整型选择属性(0:银色,1:黑色,2:红色,3:灰色),price全精度小数类型,image图片文件类型,brand字符串类型
2、基于ModelSerializer类,完成Car资源的单查,群查,单增接口
序列化:显示车名,车的颜色,车的价格,车的海报,车的品牌
反序列化:必须提供车名,车的价格,车的品牌(车的匹配需要二次确认re_brand),车的颜色默认为银色(可以提供),车的海报不需要提供(默认为空)
代码
#urls
from django.conf.urls import url,include
from django.contrib import admin
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/',include('api.urls')),
url(r'^media/(?P<path>.*)',serve,{'document_root':settings.MEDIA_ROOT})
]
#view
from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models,serializers
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'
})
car_ser = serializers.CarModelSerializer(car_obj)
return Response({
'status':0,
'msg':'ok',
'results':car_ser.data
})
car_query = models.Car.objects.all()
car_ser = serializers.CarModelSerializer(car_query,many=True)
return Response({
'status':0,
'msg':'ok',
'results':car_ser.data
})
def post(self,request,*args,**kwargs):
car_ser = serializers.CarModelSerializer(data=request.data)
#校验不通过会自动抛出异常,代码不会继续往下执行
car_ser.is_valid(raise_exception=True)
car_obj = car_ser.save()
return Response({
'status':0,
'msg':'ok',
'results':serializers.CarModelSerializer(car_obj).data
})
#model
from django.db import models
# Create your models here.
class Car(models.Model):
COLOR_CHOICES = [(0,'银色'),(1,'黑色'),(2,'红色'),(3,'灰色')]
name = models.CharField(max_length=64)
colors = models.IntegerField(choices=COLOR_CHOICES,default=0)
price = models.DecimalField(max_digits=10,decimal_places=2)
brand = models.CharField(max_length=64)
image = models.ImageField(upload_to='img',default='img/default.png')
@property
def car_color(self):
return self.get_colors_display()
#serializers
from rest_framework import serializers
from . import models
class CarModelSerializer(serializers.ModelSerializer):
re_brand = serializers.CharField(write_only=True)
class Meta:
model = models.Car
#指向序列化反序列化的models类
fields = ['name','price','color','car_color','image','brand','re_brand']
extra_kwargs = {
'image':{
'read_only':True
},
'color':{
'write_only':True
}
}
def validate(self,attrs):
brand = attrs.get('brand')
re_brand = attrs.pop('re_brand')
if brand != re_brand:
raise serializers.ValidationError({'re_brand':'品牌输入不正确'})
return attrs