from django.urls import path, re_path
from .views import BookView,PublsihView,AuhthorView
from rest_framework.versioning import URLPathVersioning
urlpatterns=[
re_path('^(?P<version>[v1|v2]+)/book/$',BookView.as_view({"get": 'list','post': 'create'})
),
re_path(r'^(?P<version>[v1|v2]+)/book/(?P<id>d+)/$', BookView.as_view({'get':'retrieve'})), #{'get':'retrieve'}
path('author', AuhthorView.as_view()),
path('publish', PublsihView.as_view())
]
用法:官方
视图:
class BookView(ModelViewSet):
""" 视图简化案例"""
lookup_field = 'id'
queryset = Book.objects.all()
serializer_class = SerializerBook
请求:
源代码加打印位置:
全局配置settings.py
REST_FRAMEWORK={
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
"DEFAULT_VERSION": 'v1', # 默认为1
"ALLOWED_VERSIONS": ['v1', 'v2'], # 仅允许v1或者v2访问
"VERSION_PARAM": 'version',
}
局部配置:
class BookView(ModelViewSet):
""" 视图简化案例"""
# 局部配置版本
versioning_class = URLPathVersioning
lookup_field = 'id'
queryset = Book.objects.all()
serializer_class = SerializerBook