我阅读了有关Django中的 View 集的信息,但并没有完全理解所有内容。
例如,在Django中使用 View 集时-
class SnippetViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
@detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
def highlight(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
和路由像这样
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
在 View 的注释中,他们说-“此 View 集自动提供
list
,create
,retrieve
,update
和destroy
操作。”编辑:::
@detail_route(methods=['post'])
def register(request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
user = User.objects.create_user(
username = serializer.init_data['username'],
password = serializer.init_data['password'],
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
最佳答案
您可以通过指定相应的HTTP方法来访问这些操作,这是REST的核心思想。即,使用HTTP方法执行其名称所暗示的操作。
GET /snippets/
-列出摘录对象POST /snippets/
-创建一个新对象PATCH /snippets/
-创建一个新对象GET /snippets/42
-检索主键为42 PUT/PATCH /snippets/42
-使用42 DELETE /snippets/42
-删除主键为42 要查看所有生成的和推断的URL正则表达式,请放入Django in debug mode并向无效的URL发出请求。它将打印出类似以下内容的内容:
Using the URLconf defined in my_app.urls, Django tried these URL patterns, in this order:
^ ^$ [name='api-root']
^ ^\.(?P<format>[a-z0-9]+)$ [name='api-root']
^ ^AltEmail/$ [name='altemail-list']
^ ^AltEmail/\.(?P<format>[a-z0-9]+)$ [name='altemail-list']
^ ^AltEmail/(?P<pk>[^/.]+)/$ [name='altemail-detail']
^ ^AltEmail/(?P<pk>[^/.]+)/\.(?P<format>[a-z0-9]+)$ [name='altemail-detail']
[...]