视图类
from rest_framework.viewsets import ViewSetMixin, GenericViewSet, ViewSet, ModelViewSet
from .response import APIResponse
from rest_framework.response import Response
class Car(ModelViewSet):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
# 群查
def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)
return APIResponse(status=response.data)
# 单查
def retrieve(self, request, *args, **kwargs):
response = super().retrieve(request, *args, **kwargs)
return APIResponse(status=response.data)
# 局部单改
def partial_update(self, request, *args, **kwargs):
response = super().partial_update(request, *args, **kwargs)
return APIResponse(status=response.data)
# 群改
def many_partial_update(self, request, *args, **kwargs):
request_data = request.data
try:
pks = []
for dic in request_data:
pk = dic.pop('id')
pks.append(pk)
car_query = models.Car.objects.filter(is_delete=False, pk__in=pks).all()
if len(pks) != len(car_query):
raise Exception('PK对应的数据不存在')
except Exception as e:
return Response({'detail': '%s' % e}, status=400)
car_ser = self.get_serializer(instance=car_query, data=request_data, many=True,
partial=True)
car_ser.is_valid(raise_exception=True)
car_list = car_ser.save()
return APIResponse(results=self.get_serializer(car_list, many=True).data)
# 整体单改
def update(self, request, *args, **kwargs):
response = super().update(request, *args, **kwargs)
return APIResponse(status=response.data)
# 单删
def destroy(self, request, *args, **kwargs):
car_obj = self.get_object()
car_obj.is_delete = True
car_obj.save()
return APIResponse(msg='删除成功')
# 群增
def create(self, request, *args, **kwargs):
request_data = request.data
if isinstance(request_data, list):
# 内部方法直接将data和many值传进去就可以传到序列化了
car_ser = self.get_serializer(data=request_data, many=True)
car_ser.is_valid(raise_exception=True)
car_obj = car_ser.save()
return APIResponse(msg='添加成功', results=self.get_serializer(car_obj, many=True).data)
序列化类
from rest_framework import serializers
from . import models
# 汽车表序列化
class CarModelSerializer(serializers.ModelSerializer):
class Meta:
# list_serializer_class固定写法,内部方法
list_serializer_class = CarListSerializer
model = models.Car
fields = ['name', 'color', 'price', 'img', 'color_car', 'store', 'sponsor', 'store_info',
'sponsor_list']
extra_kwargs = {
'color': {
'write_only': True
},
'sponsor': {
'write_only': True
},
'store':{
'write_only': True
}
}