Home > Mobile >  How to retrieve and map through items of a specific category with Django and react
How to retrieve and map through items of a specific category with Django and react

Time:06-23

I'm trying to fetch items of a particular category that then map through the category in react app. I created an API with Django restframework that returns items of such category but using a post request. Here is the code:

 
 ​class​ ​ProductCategoryView​(​APIView​): 
 ​    ​serializer_class​ ​=​ ​ProductSerializer 
 ​    ​permission_classes​ ​=​ (​permissions​.​AllowAny​, ) 
  
 ​    ​def​ ​post​(​self​, ​request​, ​format​=​None​): 
 ​        ​data​ ​=​ ​self​.​request​.​data 
 ​        ​category​ ​=​ ​data​[​'category'​] 
 ​        ​queryset​ ​=​ ​Product​.​objects​.​order_by​(​'-dateCreated'​).​filter​(​category__iexact​=​category​) 
 ​        ​serializer​ ​=​ ​ProductSerializer​(​queryset​, ​many​=​True​) 
 ​        ​return​ ​Response​(​serializer​.​data​)

For instance, let's say I have 3 categories of items in the database(textbooks, journals and novels). In the react frontend app, I want to retrieve only the textbooks, map through the array of textbooks and display each textbook without displaying any item from other categories. But I have challenges implementing it since I'm using post request. By passing a specific category to the body of the request I get items in that category returned. Is it possible to use get request and filter the items from the database such that I get only the items under the category called textbook?

CodePudding user response:

Yes you can implement using get as well. For searching and filtering I usually use generic ListAPIView which have nice pagination functionalities as well.

from rest_framework import generics

class ProductCategoryView​(​generics.ListAPIView​):
    serializer_class​ ​=​ ​ProductSerializer
    permission_classes​ ​=​ (​permissions​.​AllowAny​, )
    queryset = Product.objects.all()
    
    def get_queryset(self):
        category = self.request.GET.get('category')
        # other_filter = self.request.GET.get('other_filter')
        qs = super().get_queryset()
        if category:
            qs = qs.filter(​category__iexact​=​category)
        # if other_filter:
        #    qs = qs.filter(other_field=other_field)
        return qs

and your url would look like this

/product-list/?category=textbooks

/product-list/?category=textbooks&other_filter=other

If you still want to stick with your code above you can change to get as follow

def get(self, request, format=None):
    category = request.GET.get('category')
    qs = Product.objects.all()
    if category:
        qs = qs.filter(category__iexact=category)
    serializer = self.serializer_class(qs, many=True)
    return Response(serializer.data)
  • Related