Django休息框架url后缀

时间:2016-03-21 10:28:54

标签: django django-rest-framework

我有网址:

api/v1/quote/ # list
api/v1/quote/1/ # detail

我如何制作这样的新网址:

api/v1/quote/1/action

并使用参数active发送此网址上的帖子请求为true,因此它会使用来自网址的id和来自帖子的active然后执行此操作?

这方面有什么例子吗?

我有这个网址代码:

router = routers.DefaultRouter()
router.register(r'quote', QuoteViewSet)

并查看:

class QuoteViewSet(viewsets.ModelViewSet):
    queryset = Quote.active.all()
    serializer_class = QuoteSerializer

    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('created_at',)

    http_method_names = ['get', 'post', 'head']

1 个答案:

答案 0 :(得分:4)

如果您使用Viewset,则可以使用@detail_route@list_route装饰器(docs)添加额外操作

在您的情况下,它可能如下所示:

class QuoteViewSet(viewsets.ModelViewSet):
    queryset = Quote.active.all()
    serializer_class = QuoteSerializer

    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('created_at',)

    http_method_names = ['get', 'post', 'head']

    @detail_route(methods=['post'])
    def action(self, id):
       # put your code here

action方法自动创建为DefaultRouter路由器,可通过以下方式加入:

api/v1/quote/{id}/action