class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
"""
A viewset that provides default `create()`, `retrieve()`, `update()`,
`partial_update()`, `destroy()` and `list()` actions.
"""
pass
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class=UserSerializer
from django import setup
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','diango1.settings') # 在环境变量中设置配置文件
setup() # 加载配置文件
from django.contrib.auth import get_user_model
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'user', UserViewSet)
urlpatterns = router.urls
for item in urlpatterns:
#输出结果
<URLPattern '^user/$' [name='user-list']>
<URLPattern '^user\.(?P<format>[a-z0-9]+)/?$' [name='user-list']>
<URLPattern '^user/(?P<pk>[^/.]+)/$' [name='user-detail']>
<URLPattern '^user/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='user-detail']>
<URLPattern '^$' [name='api-root']>
<URLPattern '^\.(?P<format>[a-z0-9]+)/?$' [name='api-root']>
注册到url app1/urls.py
from django.contrib import admin
from django.urls import path
from rest_framework.routers import DefaultRouter
from app1.views import hello, UserViewSet
router = DefaultRouter()
router.register(r'codes', UserViewSet)
urlpatterns = [
path('app1/', hello),
path('user_list', UserViewSet.as_view({'get': 'list'})),
path('user_detail', UserViewSet.as_view({'get': 'retrieve'}))
]
urlpatterns += router.urls