分页相关
序列化相关
数据验证
序列化相关类
路由相关
代码示例
基于ModelViewSet自定制
class P2(PageNumberPagination):
page_size = 3 #每一页显示的条数
page_query_param = 'page' #获取参数中传入的页码
page_size_query_param = 'size' #获取url参数中每页显示的数据条数
max_page_size = 5 # url传入的参数的最大有效值
class IndexSerializer(ModelSerializer):
x2 = serializers.SerializerMethodField()
class Meta:
model = models.UserInfo
fields = ['name','pwd','x2']
def get_x2(self, obj):
return obj.name + 'hello word'
class IndexView(ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = IndexSerializer
pagination_class = P2
##########下面的方法对已覆盖默认的方法,进行自定制#########
def list(self, request, *args, **kwargs):
'''获取get请求的所有'''
pass
def retrieve(self, request, *args, **kwargs):
'''查看单条数据'''
pass
def destroy(self, request, *args, **kwargs):
'''删除DELETE'''
pass
def create(self, request, *args, **kwargs):
'''添加数据POST'''
pass
def update(self, request, *args, **kwargs):
'''全部修改PUT'''
pass
def partial_update(self, request, *args, **kwargs):
'''局部修改PATCH'''
pass
路由的两种方式
urlpatterns = [
url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})),
url(r'^index\.(?P[a-z0-9]+)$', views.IndexView.as_view({'get':'list','post':'create'})),
url(r'^index/(?P\d+)/$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
url(r'^index(?P\d+)\.(?P[a-z0-9]+)$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
]
router = DefaultRouter()
router.register('index',views.IndexViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]