class UserV4APIView(APIView):
def get(self,request,*args,**kwargs):
pk=kwargs.get('pk')
if pk:
user_obj=models.Car.objects.filter(is_delete=False,pk=pk).first()
if not user_obj:
return Response({
'status':1,
'msg':'pk error',
},status=400)
user_ser=serializers.CarModelSerializer(user_obj,many=False)
return Response({
'status':0,
'msg':'ok',
'results':user_ser.data
})
else:
user_query=models.Car.objects.filter(is_delete=False).all()
user_ser=serializers.CarModelSerializer(user_query,many=True)
return Response({
'status': 0,
'msg': 'ok',
'results': user_ser.data
})
def post(self,request,*args,**kwargs):
user_ser=serializers.CarModelSerializer(data=request.data)
if user_ser.is_valid():
user_obj=user_ser.save()
return Response({
'status':0,
'msg':'ok',
'results':serializers.CarModelSerializer(user_obj).data
})
else:
return Response({
'status': 1,
'msg': user_ser.errors,
})
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},
}
def validated_username(self, value):
if 'SB' in value.lower():
raise serializers.ValidationError('名字中不能含有SB')
return value
def validate(self, attrs):
brand = attrs.get('brand')
re_brand = attrs.pop('re_brand')
if re_brand != brand:
raise serializers.ValidationError({'re_brand': '两次输入不一致'})
return attrs
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='img', default='img/default.png', verbose_name='图片')
brand = models.CharField(max_length=64, verbose_name='厂商')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
@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)
class Meta:
verbose_name_plural = '汽车表'
def __str__(self):
return self.name