72
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
from .response import APIResponse
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)
return APIResponse(1, 'pk error', http_status=400)
car_data = serializers.CarModelSerializer(car_obj).data
# return Response({
# 'status': 0,
# 'msg': 'ok',
# 'results': car_data
# })
return APIResponse(results=car_data)
car_query = models.Car.objects.all()
# return Response({
# 'status': 0,
# 'msg': 'ok',
# 'results': serializers.CarModelSerializer(car_query, many=True).data
# })
# 不喜欢results作为数据的key,也可以更换
return APIResponse(0, 'ok', data=serializers.CarModelSerializer(car_query, many=True).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
# })
return APIResponse(results=serializers.CarModelSerializer(car_obj).data)
class PublishAPIView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
publish_obj = models.Publish.objects.filter(pk=pk).first()
if not publish_obj:
return APIResponse(1, 'pk error', http_status=400)
publish_data = serializers.PublishModelSerializer(publish_obj).data
return APIResponse(results=publish_data)
publish_query = models.Publish.objects.all()
return APIResponse(0, 'ok', data=serializers.PublishModelSerializer(publish_query, many=True).data)
class BookAPIView(APIView):
# 单查、群查
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
book_obj = models.Book.objects.filter(pk=pk, is_delete=False).first()
if not book_obj:
return APIResponse(1, 'pk error', http_status=400)
book_data = serializers.BookModelSerializer(book_obj).data
return APIResponse(results=book_data)
book_query = models.Book.objects.filter(is_delete=False).all()
return APIResponse(0, 'ok', data=serializers.BookModelSerializer(book_query, many=True).data)
# 单删、群删
def delete(self, request, *args, **kwargs):
"""
单删:前台数据为pk,接口为 /books/(pk)/
群删:前台数据为pks,接口为 /books/
"""
pk = kwargs.get('pk')
# 将单删群删逻辑整合
if pk: # /books/(pk)/的接口就不考虑群删,就固定为单删
pks = [pk]
else:
pks = request.data.get('pks')
# 前台数据有误(主要是群删没有提供pks)
if not pks:
return APIResponse(1, 'delete error', http_status=400)
# 只要有操作受影响行,就是删除成功,反之失败
rows = models.Book.objects.filter(is_delete=False, pk__in=pks).update(is_delete=True)
if rows:
return APIResponse(0, 'delete ok')
return APIResponse(1, 'delete failed')
# 单增、群增
def post(self, request, *args, **kwargs):
"""
单增:前台提交字典,接口 /books/
群增:前台提交列表套字典,接口 /books/
"""
request_data = request.data
if isinstance(request_data, dict): # 单增
book_ser = serializers.BookModelSerializer(data=request_data)
if book_ser.is_valid():
book_obj = book_ser.save()
return APIResponse(results=serializers.BookModelSerializer(book_obj).data)
return APIResponse(1, msg=book_ser.errors)
elif isinstance(request_data, list) and len(request_data) != 0 : # 群增
book_ser = serializers.BookModelSerializer(data=request_data, many=True)
book_ser.is_valid(raise_exception=True)
book_obj_list = book_ser.save()
return APIResponse(results=serializers.BookModelSerializer(book_obj_list, many=True).data)
else:
return APIResponse(1, 'data error', http_status=400)
# 单整体改、群整体改
def put(self, request, *args, **kwargs):
"""
单整体改:前台提交字典,接口 /books/(pk)/
群整体改:前台提交列表套字典,接口 /books/,注每一个字典都可以通过pk
"""
pk = kwargs.get('pk')
request_data = request.data
if pk: # 单改
try:
book_obj = models.Book.objects.get(pk=pk)
except:
return APIResponse(1, 'pk error')
# 修改和新增,都需要通过数据,数据依旧给data,修改与新增不同点,instance要被赋值为被修改对象
book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data)
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return APIResponse(results=serializers.BookModelSerializer(book_obj).data)
else: # 群改
if not isinstance(request_data, list) or len(request_data) == 0:
return APIResponse(1, 'data error', http_status=400)
# [{pk:1,...}, {pk:3,...}, {pk:100,...}] => [obj1, obj3, obj100] + [{...}, {...}, {...}]
# 要考虑pk对应的对象是否被删,以及pk没有对应的对象
# 假设pk3被删,pk100没有 => [obj1] + [{...}]
# 注:一定不要在循环体中对循环对象进行增删(影响对象长度)的操作
obj_list = []
data_list = []
for dic in request_data:
# request_data可能是list,单内部不一定是dict
try:
pk = dic.pop('pk')
try:
obj = models.Book.objects.get(pk=pk, is_delete=False)
obj_list.append(obj)
data_list.append(dic)
except:
pass
except:
return APIResponse(1, 'data error', http_status=400)
book_ser = serializers.BookModelSerializer(instance=obj_list, data=data_list, many=True)
book_ser.is_valid(raise_exception=True)
book_obj_list = book_ser.save()
return APIResponse(results=serializers.BookModelSerializer(book_obj_list, many=True).data)
# 单局部改、群局部改
def patch(self, request, *args, **kwargs):
"""
单整体改:前台提交字典,接口 /books/(pk)/
群整体改:前台提交列表套字典,接口 /books/,注每一个字典都可以通过pk
"""
pk = kwargs.get('pk')
request_data = request.data
if pk:
try:
book_obj = models.Book.objects.get(pk=pk)
except:
return APIResponse(1, 'pk error')
# 局部修改就是在整体修改基础上设置partial=True,将所有参与反序列化字段设置为required=False
book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data, partial=True)
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return APIResponse(results=serializers.BookModelSerializer(book_obj).data)
else: # 群改
if not isinstance(request_data, list) or len(request_data) == 0:
return APIResponse(1, 'data error', http_status=400)
# [{pk:1,...}, {pk:3,...}, {pk:100,...}] => [obj1, obj3, obj100] + [{...}, {...}, {...}]
# 要考虑pk对应的对象是否被删,以及pk没有对应的对象
# 假设pk3被删,pk100没有 => [obj1] + [{...}]
# 注:一定不要在循环体中对循环对象进行增删(影响对象长度)的操作
obj_list = []
data_list = []
for dic in request_data:
# request_data可能是list,单内部不一定是dict
try:
pk = dic.pop('pk')
try:
obj = models.Book.objects.get(pk=pk, is_delete=False)
obj_list.append(obj)
data_list.append(dic)
except:
pass
except:
return APIResponse(1, 'data error', http_status=400)
book_ser = serializers.BookModelSerializer(instance=obj_list, data=data_list, many=True, partial=True)
book_ser.is_valid(raise_exception=True)
book_obj_list = book_ser.save()
return APIResponse(results=serializers.BookModelSerializer(book_obj_list, many=True).data)