Ahmed Wagdi
Ahmed Wagdi

Reputation: 4401

How to request a filtered viewset in django restframwork

I need to retrieve a filtered set of data by calling an HTTP request using Django rest framework.

here are my API codes:

urls.py

urlpatterns = [
    path('api/get_products/', views.get_products),
]

Views.py

@api_view(["GET", ])
def get_products(request):
    category_name = request.data['category_name']
    category_obj = Category.objects.get(name=category_name)
    products_list = Product.objects.filter(category=category_obj)
    serializer = ProductSerializers(products_list)
    return Response(serializer.data)

and finally the serialierz.py

class CategorySerializers(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Category
        fields = ['name', 'id']


class ProductSerializers(serializers.HyperlinkedModelSerializer):
    category = CategorySerializers()

    class Meta:
        model = Product
        fields = '__all__'

and am trying to call it using a get request with the argument: {'category_name':'the_name_of_the_category' }

and it returns this error:

KeyError at /categories/api/api/get_products/
'category_name'

Upvotes: 1

Views: 47

Answers (1)

kamilyrb
kamilyrb

Reputation: 2627

Your API method is a GET method. You cannot accept body with get method. You can change your API method with POST method or better one, you can get 'category_name' with url. You can add url variable like that:

path('api/get_products/<slug:category_name>', views.get_products),

and your view method:

def get_products(request,category_name):
    category_obj = Category.objects.get(name=category_name)
    products_list = Product.objects.filter(category=category_obj)
    serializer = ProductSerializers(products_list)
    return Response(serializer.data)

Upvotes: 1

Related Questions