'Putting if else conditions in Django Rest Framework API View while searching
I was writing API with DRF and what I want is to change queryset, if the search will return no results.
from rest_framework.generics import ListAPIView
from rest_framework import filters
from .models import Item
from .serializer import ItemSerializer
from .pagination import ItemPagination
class SearchItemApi(ListAPIView):
serializer_class = ItemSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['name',]
pagination_class = ItemPagination
def get_queryset(self):
return Item.objects.all()
Here is the serializer:
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'name',)
And this APIView will show these results on the page:
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "Blue Jeans",
},
{
"id": 2,
"name": "Red Jeans",
}
]
}
And I want to make something like this:
def get_queryset(self):
if api_data["count"] == 0:
return Item.objects.filter(*some filter*)
else:
return Item.objects.all()
How can I add a condition to return other queryset, if the search will bring zero results?
Solution 1:[1]
You need to check the queryset result
def get_queryset(self):
qs = super().get_queryset()
if qs.count() == 0:
return Item.objects.filter(*some filter*)
else:
return Item.objects.all()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hendrikschneider |
