from django.urls import path,re_path
from api import views
urlpatterns = [
path('books/', views.BookAPIView.as_view()),
re_path('books/(?P<pk>\d+)', views.BookAPIView.as_view()),
]
from rest_framework.response import Response
from api import models
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from api.ser import BookModelSerializer
classBookAPIView(APIView):
defget(self,request,*args,**kwargs):
book_list=models.Book.objects.all().filter(is_delete=False)
book_list_ser=BookModelSerializer(book_list,many=True)
return Response(data=book_list_ser.data)
defpost(self,request,*args,**kwargs):
if isinstance(request.data,dict):
book_ser=BookModelSerializer(data=request.data)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
elif isinstance(request.data,list):
from rest_framework.serializers import ListSerializer
book_ser = BookModelSerializer(data=request.data,many=True)
print('--------',type(book_ser))
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
defput(self,request,*args,**kwargs):
if kwargs.get('pk',None):
book=models.Book.objects.filter(pk=kwargs.get('pk')).first()
book_ser = BookModelSerializer(instance=book,data=request.data,partial=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
else:
book_list=[]
modify_data=[]
for item in request.data:
pk=item.pop('id')
book=models.Book.objects.get(pk=pk)
book_list.append(book)
modify_data.append(item)
book_ser = BookModelSerializer(instance=book_list,data=modify_data,many=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(book_ser.data)
defdelete(self,request,*args,**kwargs):
pk=kwargs.get('pk')
pks=[]
if pk:
pks.append(pk)
else:
pks=request.data.get('pks')
ret=models.Book.objects.filter(pk__in=pks,is_delete=False).update(is_delete=True)
if ret:
return Response(data={'msg':'删除成功'})
else:
return Response(data={'msg': '没有要删除的数据'})
ser.py
from rest_framework import serializers
from api import models
classBookListSerializer(serializers.ListSerializer):
defupdate(self, instance, validated_data):
print(instance)
print(validated_data)
return [
self.child.update(instance[i],attrs) for i,attrs in enumerate(validated_data)
]
classBookModelSerializer(serializers.ModelSerializer):
classMeta:
list_serializer_class=BookListSerializer
model=models.Book
fields = ('name','price','authors','publish','publish_name','author_list')
extra_kwargs={
'publish':{'write_only':True},
'publish_name':{'read_only':True},
'authors':{'write_only':True},
'author_list':{'read_only':True}
}
from django.db import models
from django.contrib.auth.models import AbstractUser
classBaseModel(models.Model):
is_delete=models.BooleanField(default=False)
create_time=models.DateTimeField(auto_now_add=True)
last_update_time=models.DateTimeField(auto_now=True)
classMeta:
abstract=True
classBook(BaseModel):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32,verbose_name='书名',help_text='这里填书名')
price=models.DecimalField(max_digits=5,decimal_places=2)
publish=models.ForeignKey(to='Publish',on_delete=models.DO_NOTHING,db_constraint=False)
authors=models.ManyToManyField(to='Author',db_constraint=False)
classMeta:
verbose_name_plural='书表'
def__str__(self):
return self.name
@property
defpublish_name(self):
return self.publish.name
defauthor_list(self):
author_list=self.authors.all()
return [ {'name':author.name,'sex':author.get_sex_display()}for author in author_list]
classPublish(BaseModel):
name = models.CharField(max_length=32)
addr=models.CharField(max_length=32)
def__str__(self):
return self.name
classAuthor(BaseModel):
name=models.CharField(max_length=32)
sex=models.IntegerField(choices=((1,'男'),(2,'女')))
authordetail=models.OneToOneField(to='AuthorDetail',db_constraint=False,on_delete=models.CASCADE)
classAuthorDetail(BaseModel):
mobile=models.CharField(max_length=11)
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination
'''
PageNumberPagination
page_size:每页显示的条数
'''
classMyPageNumberPagination(PageNumberPagination):
page_size=3
page_query_param='aaa'
page_size_query_param='size'
max_page_size=5
classMyCursorPagination(CursorPagination):
cursor_query_param = 'cursor'
page_size = 2
ordering = '-id'
from utils.throttling import MyThrottle
classBookView(APIView):
defget(self,request,*args,**kwargs):
book_list=models.Book.objects.all()
page_cursor=MyPageNumberPagination()
book_list=page_cursor.paginate_queryset(book_list,request,view=self)
next_url =page_cursor.get_next_link()
pr_url=page_cursor.get_previous_link()
book_ser=BookModelSerializer(book_list,many=True)
return Response(data=book_ser.data)
REST_FRAMEWORK={
'PAGE_SIZE': 2,
}
from rest_framework.throttling import ScopedRateThrottle,SimpleRateThrottle
classMyThrottle(SimpleRateThrottle):
scope='luffy'
defget_cache_key(self, request, view):
print(request.META.get('REMOTE_ADDR'))
return request.META.get('REMOTE_ADDR')
REST_FRAMEWORK={
'DEFAULT_THROTTLE_CLASSES': (
'utils.throttling.MyThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'luffy': '3/m'
},
}