Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework: Get url path variable in a view

I have to pass the product_id (which is a string) into a view. There I have to do some DB operations based on the product id. How can I get that product id in that view? Actually what should be the parameter in the class ProductDetailConfiguration view? Now I am passing viewsets.ModelViewSet. Actually, this API call is not completely related to any model.

# urls.py

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

# views.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
like image 343
Arun SS Avatar asked Apr 19 '17 06:04

Arun SS


Video Answer


1 Answers

The URL parameters are available in self.kwargs.
From the documentation:

Filtering against the URL

Another style of filtering might involve restricting the queryset based on some part of the URL.

For example if your URL config contained an entry like this:

url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),

You could then write a view that returned a purchase queryset filtered by the username portion of the 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)
like image 106
OrangeDog Avatar answered Oct 21 '22 07:10

OrangeDog