Home > Back-end >  Django -how to pass value in dynamic url into queryset
Django -how to pass value in dynamic url into queryset

Time:11-14

I have a dynamic url that will display the same page but with specific data depending on the value that is in the url.

I'm trying to set up a View that will return the filtered data based on the value in the url but i don't know how to pass value in the url into the queryset.

Views.py:

from rest_framework import permissions
from .serializers import ProductSerializer,CategorySerializer
from .models import Product,Category
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
class ProductViewSet(viewsets.ModelViewSet):
    queryset=Product.objects.all()
    serializer_class= ProductSerializer

class CategoryViewSet(viewsets.ModelViewSet):
    queryset=Category.objects.all()
    serializer_class= CategorySerializer

class ProductbyCategory(viewsets.ModelViewSet):
    categoryid=1
    def __init__(self,request,categoryid):
        self.categoryid=categoryid
    queryset=Product.objects.filter(categoryid=categoryid)
    serializer_class= ProductSerializer

Urls.py

from .views import ProductViewSet,CategoryViewSet,ProductbyCategory
from rest_framework import routers
from .serializers import ProductSerializer,CategorySerializer
from .models import Product,Category

router = routers.DefaultRouter()
router.register(r'products', ProductViewSet)
router.register(r'category', CategoryViewSet)
router.register(r'sort-by-category/<int:categoryid>', ProductbyCategory)

urlpatterns = [
    path('',include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
] 

Any help would be greatly appreciated

CodePudding user response:

You can override the get_queryset method:

Views.py

class ProductbyCategory(viewsets.ModelViewSet):
    serializer_class= ProductSerializer

    def get_queryset(self):
        categoryid = self.kwargs['categoryid'] 
        return Product.objects.filter(categoryid=categoryid)

CodePudding user response:

# You have to override get_queryset method

class ProductbyCategory(viewsets.ModelViewSet):
    serializer_class= ProductSerializer
    def get_queryset(self):
        categoryid = self.request.query_params.get('categoryid')
        queryset=Product.objects.filter(categoryid=categoryid)
        return queryset
  • Related