django rest 框架:在视图中获取 url 路径变量

Aru*_* SS 11 python django django-models django-views django-rest-framework

我必须将product_id(这是一个字符串)传递到视图中。在那里我必须根据产品 ID 进行一些数据库操作。如何在该视图中获取该产品 ID?实际上类ProductDetailConfiguration视图中的参数应该是什么?现在我路过viewsets.ModelViewSet。实际上,这个 API 调用并不与任何模型完全相关。

# urls.py

  url(r'^product-configuration/(?P<product_id>[\w-]+)/$', views.ProductDetailConfiguration, name='product-configuration'),
Run Code Online (Sandbox Code Playgroud)

# 视图.py

class ProductDetailConfiguration(viewsets.ModelViewSet):

    queryset = Product.objects.all()

    def get_queryset(self, **kwargs):
      
        queryset = Product.objects.all()
        product_id = self.request.get('product_id', None)
        #filter query set based on the product_id
        return queryset

    serializer_class = ProductConfigurationSerializer
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 15

URL 参数在self.kwargs.
文档

根据 URL 过滤

另一种过滤方式可能涉及基于 URL 的某些部分限制查询集。

例如,如果您的 URL 配置包含这样的条目:

url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
Run Code Online (Sandbox Code Playgroud)

然后,您可以编写一个视图,该视图返回由 URL 的用户名部分过滤的购买查询集:

class PurchaseList(generics.ListAPIView):
   serializer_class = PurchaseSerializer

   def get_queryset(self):
       """
       This view should return a list of all the purchases for
       the user as determined by the username portion of the URL.
       """
       username = self.kwargs['username']
       return Purchase.objects.filter(purchaser__username=username)
Run Code Online (Sandbox Code Playgroud)


Phu*_* Vu 0

这是我的方法:

更新网址:

url(r'^product-configuration$', views.ProductDetailConfiguration, name='product-configuration'),
Run Code Online (Sandbox Code Playgroud)

在view.py中:

class ProductDetailConfiguration(viewsets.ModelViewSet):
    lookup_field = 'product_id'
    serializer_class = ProductConfigurationSerializer

    def retrieve(request, product_id=None, *args, **kwargs):
        queryset = self.get_queryset()
        # Filter with produc_id
        # print(product_id)
        # Return Response
Run Code Online (Sandbox Code Playgroud)