添加另一个参数以路由DRF

时间:2016-07-27 10:04:12

标签: django django-rest-framework

Django Rest Framework默认生成了一组API端点。举个例子:

^api/ ^ ^provinces/(?P<pk>[^/.]+)/$ [name='province-detail']

生成http://127.0.0.1:8000/api/provinces/02/这很好。 它使用下面的实际代码:

class ProvinceSerializer(serializers.ModelSerializer):
    """ Serializer to represent the Province model """
    class Meta:
        model = Province
        fields = ("name", "code")

我想添加另一个路由,以便我可以拥有另一个端点,例如:

^api/ ^ ^provinces/(?P<pk>[^/.]+)/(?P<product>[^/.]+)/$ [name='province-product-detail']

这样我可以这样做http://127.0.0.1:8000/api/provinces/02/apple/并访问序列化器方法中的第二个参数。我试图这样做:

class ProvinceSerializer(serializers.ModelSerializer):
    """ Serializer to represent the Province model """
    class Meta:
        model = Province
        fields = ("name", "code")

    @detail_route(methods=['post'])
    def set_product(self, request, product=None):
        return product

1 个答案:

答案 0 :(得分:0)

我发现我在错误的地方使用了@detail_route。我们必须这样做:

class ProvinceDistrictViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to view or edit province.
    """
    queryset = Province.objects.all()
    serializer_class = ProvinceDistrictsSerializer

    # For get provinces
    @detail_route(methods=['get'], url_path='(?P<product>\d+)')
    def update_product(self, request, pk, product=None):
        """ Updates the object identified by the pk and add the product """
        queryset = Province.objects.filter(pk=pk)
        serializer = ProvinceDistrictsSerializer(queryset, many=True, context={'product': product})
        return Response(serializer.data, status=status.HTTP_200_OK)