#### 使用 ModelViewSet 里面 ListModelMixin的 list方法
```python
class ModelGetMixin():
# def get(self, requset):
# query = self.get_queryset()
# ser_class = self.get_serializer_class() # BookSerializer
# ser = ser_class(query, many=True)
# return Response(ser.data)
def list(self, requset):
query = self.get_queryset()
ser_class = self.get_serializer_class() # BookSerializer
ser = ser_class(query, many=True)
return Response(ser.data)
{
"detail": "Method \"GET\" not allowed."
}
为了使用list方法
urls配置:
第一种方法:
path('books/',views.BookModelViewSet.as_view
({'get':'list','post':"create"})),
path('books/',views.BookModelViewSet.as_view
({'get':'retrieve','post':"update",'delete':'destory'})),
第二种方法:
from rest_framework.routers import DefaultRouter
router=DefaultRouter()
router.register('books',views.BookModelViewSet)
urlpatterns+=router.urls
用户模块 使用…List
user序列化器
= = = = user.ser = = = =
from rest_framework import serializers
from user.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
= = = = user.views 里 = = = =
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from user.models import User
from user.ser import UserSerializer
class UserModelViewSet(ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
= = = = user.urls = = = =
from django.urls import path
from rest_framework.routers import DefaultRouter
from user import views
router = DefaultRouter()
router.register('user', views.UserModelViewSet)
urlpatterns = [
]
urlpatterns += router.urls
过滤设置
pip install django-filter
配置:
INSTALLED_APPS = [
django_filters
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
],
}
排序
1.视图集添加
filter_backends = [OrderingFilter]
ordering_fields = ('id', 'bpub_date')
2.请求地址
第二页:/books/?ordering=id&page=2
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'SEARCH_PARAM': 'search',
'ORDERING_PARAM': 'ordering',
自定义分页
class StandarResultPaagination(PageNumberPagination):
page_sizr = None
pagination_class=StandarResultPaagination
为什么使用 restful
有一套url的规范 效率高 框架特别稳定
restful 处理模型 时的规范 url的写法 ->模型的操作
/user/get/?id=123 ->
获取一个 GET/user/123/
获取多个 GET/user/
创建一个 POST/user/ body{
'username':'lisi','password':'xxxx'}
修改一个 PUT/user/1/ body{
'username':'lisi','password':'xxxx'}
删除一个 DELETE /user/1
用在处理数据 大幅度增加我们的数据操作接口的开发效率
提高代码的健壮性(...) 鲁棒性 越稳定
1. 数据接口 对数据进行增删改查
2. 业务接口 发送短信 调用三方接口 数据存 redis 通常用 APIView