0

I am currently developing a search system using Django-filter. For example, if you search under the following conditions, all the displays will be returned.

Data

[
    {
        "id": 1,
        "city": "aaa",
    },
    {
        "id": 2,
        "city": "bbb",
    },
    {
        "id": 3,
        "city": "ccc",
    }
]

views.py

class CitySearchView(APIView):

    def get(self, request):

        if not request.GET:
            raise Http404()

        queryset = City.objects.all()
        filterset = FilterCity(request.query_params, queryset=queryset)
        serializer = CitySerializer(instance=filterset.qs, many=True)
        return Response(serializer.data)

filter.py

class FilterCity(filters.FilterSet):
    city = filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = City
        fields = []

Request URL there is no value.

http://127.0.0.1:8000/api/search/?city=

Response

[
    {
        "id": 1,
        "city": "aaa",
    },
    {
        "id": 2,
        "city": "bbb",
    },
    {
        "id": 3,
        "city": "ccc",
    }
]

My hope is to return the string "Not Found" or empty array[]. In that case, how should I implement it?

Thank you.

i'm fat.
  • 53
  • 7
  • Does this answer your question? [Empty result list on django-filter page startup](https://stackoverflow.com/questions/30211058/empty-result-list-on-django-filter-page-startup) – Tharun K Jul 10 '22 at 08:14
  • When you say `?city=` that means you specify an empty string as the value, given that you have `lookup_expr='icontains'` your results are correct and this should be intended behaviour. – Abdul Aziz Barkat Jul 10 '22 at 12:21
  • Does this answer your question? [Submit only non empty fields from Form](https://stackoverflow.com/questions/23532729/submit-only-non-empty-fields-from-form) – Abdul Aziz Barkat Jul 10 '22 at 12:25
  • @AbdulAzizBarkat Removing `lookup_expr='icontains'` does not seem to change the results and returns all data. – i'm fat. Jul 11 '22 at 00:53
  • The problem this time is like http://127.0.0.1:8000/api/search/?city= , when there is no value set for a particular key, and what you taught me yesterday was how to deal with cases like http://127.0.0.1:8000/api/search/, where there is neither a key nor a value The solution was to deal with the case where there is no value. – i'm fat. Jul 11 '22 at 00:54

2 Answers2

1

Django-filter STRICT filtering

from django-filter>=2.0.0, strict filtering behavior has changed. when filter does not have have any result, queryset.all() is returned. if you want to keep the 'strict' filtering style, you can try the following:

  • override django_filters.FilterSet directly
  • use custom method in filtering

Overriding FilterSet

class FilterSet(django_filters.FilterSet):

    # override
    @property
    def qs(self):
        if not hasattr(self, '_qs'):
            qs = self.queryset.all()
            if self.is_bound:
                if self.form.is_valid():
                    qs = self.filter_queryset(qs)
                else:
                    qs = self.queryset.none()
            self._qs = qs
        return self._qs

Defining custom method filter_city

class FilterCity(filters.FilterSet):
    city = filters.CharFilter(method='filter_city')

    def filter_city(self, queryset, name, value):
        # if no city, return empty queryset
        if value in [None, '']:
            return queryset.none()
        else:
            return queryset.filter(city=city)

Issues reported

NamsanCode
  • 226
  • 1
  • 4
0

You can just do

city = request.GET.get("city")

# Depending upon type of request
# city = request.POST.get("city")

City.objects.filter(city = city)
  • Thank you for your comment. I changed queryset = City.objects.all() to City.objects.filter(query_param = request.query_param) and 'Request' object has no attribute 'query_param', an error occurred. Am I modifying it in the wrong place? – i'm fat. Jul 11 '22 at 00:49
  • You need to modify query_param according to your needs. Check updated answer. – Bhavya Peshavaria Jul 11 '22 at 04:50