Django Rest Framework @detail_route收益404

时间:2015-08-28 11:20:55

标签: python django rest django-rest-framework

我有ViewSet喜欢

class CustomerViewSet(ModelViewSet):
    queryset = models.Customer.objects.all()
    serializer_class = serializers.CustomerSerializer
    filter_class = filters.CustomerFilterSet

    @detail_route
    def licenses(self, request, pk=None):
        customer = self.get_object()
        licenses = Item.objects.active().sold().for_customer(customer)
        serializer = serializers.ItemSerializer(licenses, many=True)
        return Response(serializer.data)

使用urls.py

绑定到router.register(r'customers', views.CustomerViewSet)

我可以GET /api/customersGET /api/customers/1000,但找不到GET /api/customers/1000/licenses。它给了我404。流程永远不会进入licenses方法。

我在这里查看了类似的问题,但他们使用了不正确的签名,我不这样做:def licenses(self, request, pk=None)

python 3.4.0
djangorestframework==3.2.3

编辑:再一次,我在回答后不到一分钟就找到答案......显然,装饰者需要像@detail_route()这样的括号。我认为按惯例这些总是可选的。?

2 个答案:

答案 0 :(得分:1)

对于post请求,您需要指定方法,因为detail_route装饰器默认会路由get个请求。 像这样:@detail_route(methods=['POST'])

答案 1 :(得分:-2)

默认情况下,路由器会向网址添加尾部斜杠。因此,GET /api/customers/将起作用而不是GET /api/customers。如果您不想使用尾部斜杠,可以将trailing_slash = False传递给路由器初始化程序。

E.g .-

router = DefaultRouter(trailing_slash = False)
router.register(r'customers', views.CustomerViewSet)

如果这不起作用,那么将路由器网址导入主网址的方式就会出现问题。