Django rest framework - using views
I've read about performances in django but haven't fully understood everything yet.
When using view in django, for example
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)
and Routing looks like this
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
In comments in the presentation they say - "This view is automatically provided steps list
, create
, retrieve
, update
and destroy
."
EDIT:
@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)
- How do I access each of these methods? and How do I access the selection method?
- The url registered with the router is / fragments. Am I doing fragments / creating? or fragments / delete?
- What does ModelViewSet really do for a URL structure?
source to share
You access these actions by specifying the appropriate HTTP method, which is the core idea in REST . Namely, using HTTP methods to do what their name suggests.
-
GET /snippets/
- list of fragment objects -
POST /snippets/
with POST data - create a new object -
PATCH /snippets/
with data - create a new object -
GET /snippets/42
- return an object with a primary key of 42 -
PUT/PATCH /snippets/42
- update object with primary key from 42 -
DELETE /snippets/42
- delete object using primary key from 42
To see all generated and inferred URLs, put Django in debug mode and query for an invalid URL. It will print something like:
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']
[...]
source to share