yernazarov
yernazarov

Reputation: 71

Can I write one viewset for List, Retrieve, Update, and Delete?

I am using a viewset.ModelViewSet to list, retrieve, update and delete Car objects. I have two urls: one ends with .as_view({'get': 'list'}) and other with .as_view({'get': 'retrieve'}), and latter one is used for updating and deleting a car object. Is it ok (won't it throw some errors in the future) or should I rewrite the PUT and DELETE in another view?

Upvotes: 1

Views: 1777

Answers (1)

Jordan Kowal
Jordan Kowal

Reputation: 1594

The point of a ViewSet is to have several endpoints/services using the same root URL. For a ModelViewSet, that means having the CRUD (Create, Read/List, Update/Patch, Delete) and any custom actions in the same viewset.

However, if using a ViewSet, I highly suggest using a router for your URL mapping, like so:

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register("cars", HealthcheckViewSet, "cars")

urlpatterns = [
    path("api/", include(router.urls), name="api"),
]

Then your URLs will be:

  • POST/LIST: api/cars/
  • UPDATE/DELETE/READ: api/cars/[id]/

Upvotes: 2

Related Questions