目前来说,url的写法有三种
from django.conf.urls import url
from api import views
app_name = 'api'
urlpatterns = [
url(r'^(?P[v1|v2]+)/view/$', views.ViewView.as_view()),
url(r'^(?P[v1|v2]+)/view/$', views.ViewView.as_view({'get': 'list', 'post': 'create'})),
url(r'^(?P[v1|v2]+)/view/(?P\d+)/$',
views.ViewView.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})
),
]
现在可以将要请求返回数据的格式写在url中
from django.conf.urls import url
from api import views
app_name = 'api'
urlpatterns = [
url(r'^(?P[v1|v2]+)/view/$', views.ViewView.as_view()),
url(r'^(?P[v1|v2]+)/view/$', views.ViewView.as_view({'get': 'list', 'post': 'create'})),
url(r'^(?P[v1|v2]+)/view\.(?P\w+)$', views.ViewView.as_view({'get': 'list', 'post': 'create'})),
url(r'^(?P[v1|v2]+)/view/(?P\d+)/$', views.ViewView.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
url(r'^(?P[v1|v2]+)/view/(?P\d+)\.(?P\w+)$', views.ViewView.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
]
通过访问url可以获取到json格式的数据
http://127.0.0.1:8000/api/v1/view.json
http://127.0.0.1:8000/api/v1/view/1.json
urls.py
from django.conf.urls import url, include
from api import views
from rest_framework import routers
routers = routers.DefaultRouter()
routers.register(r'view', views.ViewView)
app_name = 'api'
urlpatterns = [
# 自动生成上诉后四种路由
url(r'^(?P[v1|v2]+)/', include(routers.urls))
]
比较常用的有JSONRenderer、BrowsableAPIRenderer、AdminRenderer
view.py
from rest_framework.viewsets import ModelViewSet
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer, AdminRenderer
from rest_framework.pagination import PageNumberPagination
from api.models import Role
from rest_framework import serializers
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Role
fields = '__all__'
class ViewView(ModelViewSet):
renderer_classes =[JSONRenderer, BrowsableAPIRenderer, AdminRenderer]
queryset = Role.objects.all()
serializer_class = PageSerializer
pagination_class = PageNumberPagination
使用时在url后面加上 .json \ .admin 即可看到想要的数据
settings.py
REST_FRAMEWORK = {
# 渲染器
'DEFAULT_RENDERER_CLASSES': ['rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer']
}