简体   繁体   中英

How to make API for filtering objects in django based on multiple key-value pairs in GET request?

I have an API url in "urls.py" folder of my django project:-

path('tests/filter/<str:key1>/<str:value1>', FilterTests.as_view())

This works fine for the below code:-

from rest_framework import generics
from service.models import Test
from service.serializers import TestListSerializer


class FilterTests(generics.ListAPIView):
    queryset = Test.objects.all()
    serializer_class = TestListSerializer

    def get_queryset(self, *args, **kwargs):
        key1 = self.kwargs['key1']
        value1 = self.kwargs['value1']
        return Test.objects.filter(**{key1: value1})

The above code filters my Test objects based on only a single key value-pair passed in the get request. I now want to filter on a more than 1 key-value pairs.

Eg:- Filter should be: name=john&type_test=algo&count=3

How should I design the api endpoint in django and not make the url too lengthy as well? Can I use a json or map, via request body? I am a beginer to django and api development so any help would be appreciated.

You can use django-filter.

pip install django-filter

Then add 'django_filters' to Django's INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'django_filters',
    ...
]

Add the filter backend to your settings

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

add the filter backend to an individual View or ViewSet.

from django_filters.rest_framework import DjangoFilterBackend

class UserListView(generics.ListAPIView):
    ...
    filter_backends = [DjangoFilterBackend]


class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['category', 'in_stock']

If all you need is simple equality-based filtering, you can set a filterset_fields attribute on the view, or viewset, listing the set of fields you wish to filter against.

This will automatically create a FilterSet class for the given fields, and will allow you to make requests such as

http://example.com/api/products?category=clothing&in_stock=True

https://www.django-rest-framework.org/api-guide/filtering/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM