Skip to content
Advertisement

How can I add the following JSON to a new URL based on its “category”: 2?

I have a JSON array in my server in Django rest framework, but I want to filter them by category , for example some of them have 'category':1 and some of them have 'category':2 like this:

[
            {
                "id": 667,
                "image": "https://ae0g",
                "description": "GRE",
                "price": "USD .11",
                "buy": "https://sn",
                "category": 1
            },
            {
                
                "image": "https://ae04.",
                "description": "10/13 ",
                "price": ".18",
                "buy": "https://",
                "category": 2
            }
]

How can I add the following JSON to a new URL based on its "category": 2?

            "image": "https://ae04.",
            "description": "10/13 ",
            "price": ".18",
            "buy": "https://",
            "category": 2

views:

class productviewset(viewsets.ModelViewSet):
    queryset=product.objects.all()
    serializer_class = productSerializer 
    pagination_class = None

    def create(self, request):
        serialized = productSerializer(data=request.data, many=True)
        if serialized.is_valid():
            serialized.save()
            return Response(serialized.data, status=status.HTTP_201_CREATED)
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

    @action (detail=False , methods=['post']) 
    def delete(self,request):
        product.objects.all().delete()
        return Response('success')

urls:

router = routers.DefaultRouter()
router.register(r'product', productviewset,basename='product')
 

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('api/', include(router.urls)),

Advertisement

Answer

Assuming that this thingy you call “json array” is set of database objects you can apply filter as described in drf docs. So in your case it would require to override get_queryset method of ModelViewSet class.

class productviewset(viewsets.ModelViewSet):
    queryset=product.objects.all()
    serializer_class = productSerializer 
    pagination_class = None

    def get_queryset(self):
        """
        Optionally restricts the returned product to a given category,
        by filtering against a `category` query parameter in the URL.
        """
        queryset = product.objects.all()
        category = self.request.query_params.get('category')
        if category is not None:
            queryset = queryset.filter(category=category)
        return queryset

    def create(self, request):
        serialized = productSerializer(data=request.data, many=True)
        if serialized.is_valid():
            serialized.save()
            return Response(serialized.data, status=status.HTTP_201_CREATED)
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

    @action (detail=False , methods=['post']) 
    def delete(self,request):
        product.objects.all().delete()
        return Response('success')

Then, if you hit /product?category=2 it should be filtered. Also, you might want to use django-filters package, but that’s overkill in your case.

Also when you code in Django (or python in general), remember to capitalize every class name so productviewset should be ProductViewSet and so on. I highly encourage to read DRF source code, which is well written and explains a lot of things.

Advertisement