Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework filter with or condition

I am using Django Rest Framework Filter to access my data. I need to get data that answers one of two conditions. Example:

Mywebsite/api/animal/?name=lion||name=frog

The || is not working. Does anyone know how I can do this filter?

like image 559
ron Avatar asked May 31 '16 08:05

ron


People also ask

How do I filter Queryset in Django REST framework?

The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the . get_queryset() method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways.

What is DjangoFilterBackend?

The DjangoFilterBackend class is used to filter the queryset based on a specified set of fields. This backend class automatically creates a FilterSet (django_filters. rest_framework. FilterSet) class for the given fields. We can also create our own FilterSet class with customized settings.

What is Q in Django REST framework?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django. db.


1 Answers

I realize this maybe a little old but i solved it like this:

from django.db.models import Q


class FooViewSet(viewsets.ModelViewSet):
    queryset = Foo.objects.all()
    status = self.request.query_params.get('status', None)

    def get_queryset(self):
        if status is not None:
            status = status.split('|')
            query = Q()
            for x in status:
                q = Q(status=x)
                query |= q
            queryset = queryset.filter(query)
        return queryset

My url then looks like this:

example.com/api/foo/?status=test1|test2|test3

and filters like this

Foo.objects.filter(Q(status=test1)|Q(status=test2)|Q(status=test3))
like image 122
Shezan Kazi Avatar answered Oct 15 '22 12:10

Shezan Kazi