1.、新建一个django项目,定义一个Car类,有name字符串属性,color整型选择属性(0:银色,1:黑色,2:红色,3:灰色),price全精度小数类型,image图片文件类型,brand字符串类型
2、基于ModelSerializer类,完成Car资源的单查,群查,单增接口
序列化:显示车名,车的颜色,车的价格,车的海报,车的品牌
反序列化:必须提供车名,车的价格,车的品牌(车的匹配需要二次确认re_brand),车的颜色默认为银色(可以提供),车的海报不需要提供(默认为空)
"""
from django.db import models
class Car(models.Model):
COLOR_CHOICE = {
(0,'银色'),
(1,'黑色'),
(2,'红色'),
(3,'灰色'),
}
name = models.CharField(max_length=64,verbose_name='车名',blank=True,unique=True )
price = models.Decimal(max_length=8,verbose_name='价格')
img = models.ImageField(upload_to='img',default='img/default.png',verbose_name='海报')
color = models.IntegerField(choices=SEX_CHOICES,default=0,verbose_name='样式')
brand = models.CharField(max_length=8,verbose_name='品牌')
id_delete = models.BooleanField(default=False,verbose_name='是否注销')
create_time = models.DateTimeField(auto_now_add=True,verbose_name='注册时间')
class Meta:
db_table = 'owen_car'
verbose_name_plural = 'c车'
def __str__(self):
return self.username
@property
def color(self):
return self.get_color_display()
@property
def icon(self):
from django.conf import settings
return '%s%s%s' % (settings.BASE_URL, settings.MEDIA_URL, self.img)
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from . import serializers
class CarView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk: # 单查
user_obj = models.User.objects.filter(is_delete=False, pk=pk).first()
if not user_obj:
return Response({
'status': 1,
'msg': 'pk error',
}, status=400)
user_ser = serializers.Car_drf(user_obj,many=False)
return Response({
'status': 0,
'msg': 'ok',
'results': user_ser.data
})
else: #群查
user_query = models.User.objects.filter(is_delete=False).all()
user_ser = serializers.Car_drf(user_query, many=True)
return Response({
'status': 0,
'msg': 'ok',
'results': user_ser.data
})
#单增
def post(self, request, *args, **kwargs):
user_ser = serializers.Car_drf(data=request.data)
if user_ser.is_valid():
# 入库
user_obj = user_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.Car_drf(user_obj).data
})
else:
return Response({
'status': 1,
'msg': user_ser.errors,
})
from rest_framework import serializers
from django.conf import settings
from . import models
class Car_drf(serializers.ModelSerializer):
re_brand = serializers.CharField(max_length=8,verbose_name='品牌')
class Meta:
model = models.Car
fields = ('name','color','brand','icon','price','')
extra_kwargs = {
'name'{: 'max_length': 10, 'error_messages': {'max_length': '太长'}},
'color': {'read_only':True},
'price': {'write_only'},
'brend': {'write_only'},
}
def validate_username(self, value):
if 'x' in value.lower():
raise serializers.ValidationError('名字中不能有x')
return value
def validate(self,attrs):
name = attrs.get('name')
brand =attrs.get('brand')
re_brand = attrs.get('band')
if brand !=re_brand:
raise serializers.ValidationError({'re_password': '两次品牌选择不一致'})
| return attrs
原文:https://www.cnblogs.com/shaozheng/p/12099214.html