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?
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With