I have a viewset as below:
class EntryViewSet(viewsets.ModelViewSet):
queryset = Entry.objects.all()
serializer_class = EntrySerializer
permission_classes = [permissions.IsOwnerStaffOrReadOnly]
filter_backends = [DjangoFilterBackend, CustomOrderingFilter]
filterset_class = EntryFilterSet
ordering_fields = ["created_at", "last_update"]
ordering = "created_at"
@method_decorator(cache_page(60 * 5, key_prefix="entry"))
def list(self, *args, **kwargs):
return super().list(*args, **kwargs)
@method_decorator(cache_page(60 * 60, key_prefix="entry"))
def retrieve(self, *args, **kwargs):
return super().retrieve(*args, **kwargs)
...which is added to urls.py
of the related app using DefaultRouter
as:
_router.register("entries", EntryViewSet, basename="entry")
However, doing reverse("api:entry-create")
fails to find create
on my test. I also quickly check the URLs with Django Extensions subcommand show_urls
but it does not print api:entry-create
, which means it is not registered. What I do:
python manage.py show_urls | grep "api:entry"
The result is:
/api/entries/ api.viewsets.entry.EntryViewSet api:entry-list
/api/entries/<pk>/ api.viewsets.entry.EntryViewSet api:entry-detail
/api/entries/<pk>\.<format>/ api.viewsets.entry.EntryViewSet api:entry-detail
/api/entries\.<format>/ api.viewsets.entry.EntryViewSet api:entry-list
...which shows only entry-detail
and entry-list
are registered while my model clearly is not ReadOnlyModelViewSet
.
Why do I not have api:entry-create
url?
Environment
- django ^2.2
- djangorestframework ^3.12.4
CodePudding user response:
You use detail
views when you want to do something with a particular resource using its pk
(/resource/<pk>
), list
when you don't have / don't want to use a pk
. So list
can be used to GET /resource
, but also POST /resource
to create a new one. Of course, POST /resource
is mapped to the create
method.