django-rest-framework:独立的GET和PUT在同一个URL但不同的泛型视图 [英] django-rest-framework: independent GET and PUT in same URL but different generics view
问题描述
我需要在一个URL(如/ api / places / 222)中允许GET,PUT和DELETE动词,并允许每个人都使用相关的实体位置获取每个字段,但只允许使用相同的网址。
Place Entity:
- id在PUT中)
- 名称(必须始终)
- 日期(PUT中不需要但在POST中需要)
URL
url(r'^ api / places /(?P< pk> \ d +)/?$',PlacesDetail.as_view(),name ='places-detail'),
我试图使用RetrieveDestroyAPIView和UpdateAPIView,但是我无法使用一个URL。
我建议你创建一些满足您需求的串行器。
然后覆盖视图的get_serializer方法,以便视图根据http请求方法切换序列化。
这是一个快速未经测试的示例:
class PlacesDetail(RetrieveUpdateDestroyAPIView):
def get_serializer_class(self):
if self.request。方法=='POST':
serializer_class = FirstSerializer
elif self.request.method =='PUT':
serializer_class = SecondSerializer
return serializer_class
...
查看基类方法的注释:
def get_serializer_class(self):
返回要用于序列化程序的类
默认使用self .serializer_class`
如果您需要根据传入的请求提供不同的
序列化,您可能需要重写。
(例如,管理员已满erialization,其他人获得基本序列化)
...
I'm using django-rest-framework and I need to map in the URL file two generic views with the same url (iḿ already using URLs but not Routes):
I need to allow GET, PUT and DELETE verbs in just one url (like /api/places/222) and allow everyone to get every field with the related Entity Place but just allow to update (PUT) one field using the same url.
Place Entity:
- id (not required in PUT)
- name (required always)
- date (not required in PUT but required in POST)
URL
url(r'^api/places/(?P<pk>\d+)/?$', PlacesDetail.as_view(), name='places-detail'),
I tried to use RetrieveDestroyAPIView and UpdateAPIView, but I'm unable to use just one URL.
I suggest you to create a few serializers that satisfy your needs. Then override the get_serializer method of your view so that the view switches serializers according to a http request method.
This is a quick untested example:
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
...
Look at the base class method's comment:
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)
"""
...
这篇关于django-rest-framework:独立的GET和PUT在同一个URL但不同的泛型视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!