from rest_framework import serializers
from . import models
class CarModelSerializer(serializers.ModelSerializer):
re_brand = serializers.CharField(write_only=True)
class Meta:
model = models.Car
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
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'
}, status=400)
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
})