Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's different about list_route and detail_route in django-rest-framework?

like title,
what's different about list_route and detail_route in django-rest-framework?
if I want to get 1 in url xxx/books/1/,
how can I write url.py and views.py ?

like image 742
nataila Avatar asked Nov 23 '15 08:11

nataila


People also ask

What is the difference between APIView and Viewset?

APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.

What is the difference between Django and Django REST framework?

Django is the web development framework in python whereas the Django Rest Framework is the library used in Django to build Rest APIs. Django Rest Framework is especially designed to make the CRUD operations easier to design in Django. Django Rest Framework makes it easy to use your Django Server as an REST API.

What is Basename in Django REST framework?

basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.

What is meta class in Django REST framework?

The Meta class can be used to define various things about the model such as the permissions, database name, singular and plural names.


1 Answers

@list_route and @detail_route are extra actions that we can add to a ViewSet. Both provide a custom routing facility in view set. Any methods on the ViewSet decorated with @detail_route or @list_route will also be routed. list_route will give all the related records, whereas detail_route will provide only a particular record. For example, given a method like this on the UserViewSet class:

class UserViewSet(ModelViewSet):
    ...

    @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
    def set_password(self, request, pk=None):

The following URL pattern would additionally be generated:

URL pattern: ^users/{pk}/set_password/$ Name: 'user-set-password'

For more information on routers you can visit the official Django Rest Rramewrok documentation on routers.

If you want get xxx/books/1/ then your url.py and views.py should look like this.

urls.py:

url(r'^xxx/books/(?P<id>[0-9]+)$', views.myview)

views.py:

@csrf_exempt
def myview(request , id):
like image 154
Jayesh Vaghasiya Avatar answered Sep 30 '22 18:09

Jayesh Vaghasiya