Chuyển đến nội dung

Bài 16 · Views and ViewSets

Custom Actions on ViewSets

Add endpoints beyond CRUD with DRF's @action decorator: detail and list actions, url_path, per-action permissions and serializers, with runnable examples.

CRUD covers most of an API, but real resources do more: publish an article, archive an order, change a password, list the five newest items, mark all notifications as read. Those are not "create a thing" or "update a thing", and cramming them into PATCH bodies makes clients awkward. DRF's @action decorator lets you add extra endpoints to a viewset that the router publishes next to the standard ones.

The decorator

Python
from rest_framework.decorators import action

class ArticleViewSet(viewsets.ModelViewSet):
    ...

    @action(detail=True, methods=["post"])
    def publish(self, request, pk=None):
        ...

detail=True makes it a detail route (/articles/<pk>/publish/, operating on one object). detail=False makes it a list route (/articles/recent/, operating on the collection). methods lists the allowed verbs (default ["get"]). The method name becomes the URL segment unless you pass url_path.

Other useful arguments are url_path, url_name, and any view-level override: permission_classes, serializer_class, renderer_classes, parser_classes, throttle_classes and filter_backends. They apply only to this action.

Detail and list actions in practice

A router publishes actions, and the test client then calls them by URL. Routers are covered in the next chapter; the two lines below are all you need for now.

Python publish and recent actions

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Observe the details:

  • self.get_object() works in a detail action, so a missing id yields 404 and object-level permissions still run.
  • self.get_serializer(...) and self.get_queryset() are available, so the action reuses the viewset's configuration.
  • The URL for latest is recent/ because of url_path. The method name stays free for readable Python.
  • A GET to a POST-only action returns 405. Without methods=["post"], a state-changing endpoint would answer GET, which is a bug: GET must never change data.

Use POST (or PUT/PATCH/DELETE) for actions that change state. Browsers, crawlers and prefetchers issue GET requests freely, so a GET that publishes, deletes or charges will eventually be triggered by accident.

Per-action serializers and permissions

An action often takes its own input shape. A password change needs old_password and new_password, not the whole user. Give the action its own serializer, and its own permissions if needed.

Python An action with its own serializer and permission

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The viewset is read-only, yet the extra action is writable. Actions are independent of the viewset's base class, which is the point: you extend a resource without opening up every verb. Notice the plain serializers.Serializer for the password input. It is not tied to a model, because the action's job is not a model update.

How actions appear in the API

  • The router lists them at the viewset's root, and the browsable API shows buttons for them.
  • Their URL names are <basename>-<url_name> (here user-set-password), so reverse("user-set-password", args=[1]) works. Set url_name to change that, as with url_path.
  • Inside the action, self.action is the method name ("set_password"), which get_permissions() and get_serializer_class() overrides can test.

Design tips

  • Prefer a noun-based resource when you can: POST /orders/ is better than POST /orders/create/. Use actions for real verbs: publish, cancel, archive, refund.
  • Keep each action small and delegate rules to model methods, so the same rule works in admin, tasks and tests.
  • Use detail=False for aggregates and searches that do not belong to one object (/orders/stats/).
  • Return the updated object (200) or 204 No Content; do not invent a new response style per action.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does detail=True mean in @action?

    detail=True creates /resource/<pk>/<action>/; detail=False creates /resource/<action>/ for the collection.
  2. 2. How do you change the URL segment of an action without renaming the method?

    url_path controls the URL segment; url_name controls the route name.
  3. 3. Why should an action that changes data not accept GET?

    GET is defined as safe; state changes belong to POST, PUT, PATCH or DELETE.
  4. 4. How can one action use a different serializer from the rest of the viewset?

    @action accepts view-level overrides such as serializer_class and permission_classes that apply only to that action.

Summary

  • @action(detail=..., methods=[...]) adds endpoints beyond CRUD to a viewset.
  • detail=True works on one object; detail=False works on the collection.
  • url_path, url_name, serializer_class and permission_classes customize one action.
  • get_object(), get_serializer() and get_queryset() work inside actions.
  • Use POST for anything that changes state, and reserve actions for real verbs.

Next: Routers: Automatic URL Configuration

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.