django-rest-framework:相同URL中的独立GET和PUT,但不同的泛型视图

Jua*_*via 12 get put django-rest-framework

我正在使用django-rest-framework,我需要在URL文件中映射两个具有相同url的通用视图(iḿ已经使用了URL而不是Routes):

我需要在一个url(例如/ api/places/222)中允许GET,PUT和DELETE动词,并允许每个人使用相关的Entity Place获取每个字段,但只允许使用相同的url更新(PUT)一个字段.

放置实体:

- id (not required in PUT)
- name (required always)
- date (not required in PUT but required in POST)
Run Code Online (Sandbox Code Playgroud)

网址

url(r'^api/places/(?P<pk>\d+)/?$', PlacesDetail.as_view(), name='places-detail'),
Run Code Online (Sandbox Code Playgroud)

我尝试使用RetrieveDestroyAPIView和UpdateAPIView,但我不能只使用一个URL.

And*_*dov 17

我建议你创建一些满足你需求的序列化器.然后覆盖视图的get_serializer方法,以便视图根据http请求方法切换序列化程序.

这是一个未经测试的快速示例:

class PlacesDetail(RetrieveUpdateDestroyAPIView):

    def get_serializer_class(self):
        if self.request.method == 'POST':
            serializer_class = FirstSerializer
        elif self.request.method == 'PUT':
            serializer_class = SecondSerializer

        return serializer_class
    ...

Run Code Online (Sandbox Code Playgroud)

查看基类方法的注释:

def get_serializer_class(self):
    """
    Return the class to use for the serializer.
    Defaults to using `self.serializer_class`.

    You may want to override this if you need to provide different
    serializations depending on the incoming request.

    (Eg. admins get full serialization, others get basic serialization)
    """
    ...
Run Code Online (Sandbox Code Playgroud)