基于ModelSerializer类,完成Car资源的单查,群查,单增接口
序列化:显示车名,车的颜色,车的价格,车的海报,车的品牌
反序列化:必须提供车名,车的价格,车的品牌(车的匹配需要二次确认re_brand),车的颜色默认为银色(可以提供),车的海报不需要提供(默认为空)
models模型类
class Car(models.Model):
COLOR_CHOICE = (
(0, '银色'),
(1, '黑色'),
(2, '红色'),
(3, '灰色')
)
name = models.CharField(max_length=64, verbose_name='名字', blank=True)
color = models.IntegerField(choices=COLOR_CHOICE, default=0, verbose_name='颜色')
price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='价格')
image = models.ImageField(upload_to='car', default='car/default.png', verbose_name='图片')
brand = models.CharField(max_length=64, verbose_name='厂商')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
is_delete = models.BooleanField(default=False, verbose_name='是否删除')
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
verbose_name_plural = <span class="hljs-string">'汽车表'</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span><span class="hljs-params">(self)</span>:</span>
<span class="hljs-keyword">return</span> self.name
<span class="hljs-comment"># 自定义序列化字段(插拔式,官方提倡使用)</span>
@property
def car_car(self):
return self.get_color_display()
@property
def img(self):
from django.conf import settings
return '%s%s%s' % (settings.BASE_URL, settings.MEDIA_URL, self.image)
路由配置
urlpatterns = [
# ModelSerializer 序列化
url(r'^v3/cars/$',views.CarV3View.as_view()),
url(r'^v3/cars/(?P<pk>\d+)/$',views.CarV3View.as_view()),
]
视图配置
class CarV3View(APIView):
# 单查群查
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
# 单查
car_obj = models.Car.objects.filter(pk=pk, is_delete=False).first()
if not car_obj:
return Response({'status': 1, 'msg': 'geterror'}, status=400)
car_dict = serializers.CarModelSerializer(car_obj, many=False).data
return Response({'status': 0, 'msg': 'ok', 'results': car_dict})
else:
# 群查
car_query = models.Car.objects.filter(is_delete=False).all()
car_dict = serializers.CarModelSerializer(car_query, many=True).data
return Response({'status': 0, 'msg': 'ok', 'results': car_dict})
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">post</span><span class="hljs-params">(self, request, *args, **kwargs)</span>:</span>
car_obj = serializers.CarModelSerializer(data=request.data)
<span class="hljs-keyword">if</span> car_obj.is_valid():
<span class="hljs-comment"># 入库</span>
car_obj = car_obj.save()
print(car_obj)
<span class="hljs-keyword">return</span> Response({<span class="hljs-string">'status'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'msg'</span>: <span class="hljs-string">'ok'</span>, <span class="hljs-string">'results'</span>: serializers.CarModelSerializer(car_obj).data})
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">return</span> Response({<span class="hljs-string">'status'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'msg'</span>: car_obj.errors})</code></pre>
序列化组件配置
class CarModelSerializer(serializers.ModelSerializer):
re_brand = serializers.CharField(min_length=3,max_length=8,write_only=True)
class Meta:
model = models.Car
fields = ('name','car_car','img','price','brand','re_brand')
extra_kwargs = {
'name':{
'min_length':3,
'max_length':8,
'error_messages':{
'min_length':'太短',
'max_length':'太长'
}
},
'car_car':{'read_only':True,'required':False},
'img':{'read_only':True},
}
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">validated_username</span><span class="hljs-params">(self,value)</span>:</span>
<span class="hljs-keyword">if</span> <span class="hljs-string">'SB'</span> <span class="hljs-keyword">in</span> value.lower():
<span class="hljs-keyword">raise</span> serializers.ValidationError(<span class="hljs-string">'名字中不能含有SB'</span>)
<span class="hljs-keyword">return</span> value
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">validate</span><span class="hljs-params">(self, attrs)</span>:</span>
brand = attrs.get(<span class="hljs-string">'brand'</span>)
re_brand = attrs.pop(<span class="hljs-string">'re_brand'</span>)
<span class="hljs-keyword">if</span> re_brand != brand:
<span class="hljs-keyword">raise</span> serializers.ValidationError({<span class="hljs-string">'re_brand'</span>:<span class="hljs-string">'两次输入不一致'</span>})
<span class="hljs-keyword">return</span> attrs</code></pre>