Django Rest框架自定义

时间:2016-01-26 22:52:54

标签: python django django-forms django-rest-framework

目前这是urls.py中的内容:

router = DefaultRouter()
router.register(r'users', views.UserViewSet)

urlpatterns = [
   url(r'^', include(router.urls)),
   url(r'^users/$', views.UserList.as_view(), name='user-list'),
   url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))

views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class StoreList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'name')

我想这样做,以便当我对网站执行POST命令时,我可以执行自定义函数,例如:

POST http://example.com/users/1/add {'id': 'joe', 'name' = 'joe1'}

POST http://example.com/users/1/add?id=joe&name=joe1

将使用输入add = id执行joe函数。所以在函数内部我可以做类似的事情:

if id == 'john':
  return Response("NO")
else:
  return Response("Yes")

然后它将返回打印输出例如

HTTP/1.0 200 OK
Content-Encoding: gzip
Content-Language: en-us
Content-Length: 123
Content-Type: application/json
Date: Tue, 26 Jan 2016 11:11:11 GMT
Expires: Tue, 26 Jan 2016 11:22:11 GMT
Handler: product-detail
Last-Modified: Tue, 26 Jan 2016 11:11:11 GMT

{
    "result": "Function success"
}

这样我的其他函数就可以使用返回的dict。

有谁知道我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

DRF有一个内置机制来帮助解决这个问题,但是根据请求,方法支持是GET。以下是文档中的参考:http://www.django-rest-framework.org/api-guide/routers/#simplerouter

解决方法可能是覆盖视图中的post函数,并将参数add作为输入。例如,

  

urls.py

url(r'users/(?P<id>[\d]+)/(?P<method>add)/$, UserListView.as_view)
  

views.py

    def post(self,request, *args, **kwargs):
         method = kwargs.get('method')   # value should be "add"
         # check if the method exist in the view
         # if yes, call it
         method_obj = getattr(self, method)
         if method_obj:
                data = request.POST #{'id':'joe}
                id = data.get('id') 
                method_obj(id=id)
   def add(self, id):
         #do soemthing
  

更新

{"id":"joe"}提供了POST数据,request,可以通过request.POST访问。