Viewset을 사용하면 관련된 view들을 하나의 클래스로 묶을 수 있다.
1 |
|
1 |
|
위의 예시는 아래의 URL 패턴을 만든다
- URL pattern:
^users/$
Name:'user-list'
- URL pattern:
^users/{pk}/$
Name:'user-detail'
- URL pattern:
^accounts/$
Name:'account-list'
- URL pattern:
^accounts/{pk}/$
Name:'account-detail'
Viewset에서 사용하는 self.action은 router가 자동으로 변환한 것이다.
URL Style | HTTP Method | Action | URL Name |
---|---|---|---|
{prefix}/ | GET | list | {basename}-list |
POST | create | ||
{prefix}/{url_path}/ | GET, or as specified by `methods` argument | `@action(detail=False)` decorated method | {basename}-{url_name} |
{prefix}/{lookup}/ | GET | retrieve | {basename}-detail |
PUT | update | ||
PATCH | partial_update | ||
DELETE | destroy | ||
{prefix}/{lookup}/{url_path}/ | GET, or as specified by `methods` argument | `@action(detail=True)` decorated method | {basename}-{url_name} |
위에 표는 URL Style + HTTP Method가 어떻게 Action으로 변환되는지를 보여준다.
만약 POST users/라고 쿼리를 보내면 {prefix}/ + POST로 action은 list가 된다.
만약 GET users/123라고 쿼리를 보내면 {prefix}/{lookup}/ + GET으로 action은 retrieve가 된다.
perform_create()는 create()가 호출된 과정에서 serializer를 사용하여 serializer.save()를 하기 위해 호출된다.
perform_create()와 create()를 구분해서 사용하는법
추가1
추가2
serializer.save()는 객체가 이미 존재하면 update를, 없다면 create를 해준다