djangodjango-rest-frameworkdjango-filters

Making Both Value to be Condition for django_filters in DRF and Showing Customized Error if the condition is empty


I am trying to use Filter in Django Restful Framework using django_filters. I would like to use two fields so the condition must be met for both fields. This means the user must enter ref_code and expecting_time. But now, if the user enters ref_code the query still works. Lastly, if the query is empty I need a customized Message.

filters.py

import django_filters
from myappointment.models import *

class AppointmentFilter(django_filters.FilterSet):
    
    class Meta:
        model = AppointmentData
        fields =['ref_code', 'expecting_time']

api.py

@api_view(['GET'])
def AllAppointmentData(request):
    queryset = AppointmentData.objects.all()
    filterset = AppointmentFilter(request.GET, queryset=queryset)

    if filterset.is_valid():
        queryset = filterset.qs
        if queryset is not None:
            serializer = AppointmentDataSerializer(queryset, many=True)
            return Response(serializer.data)
        else:
            return Response([], {'success': "The Query is empty"}, status=status.HTTP_200_BAD_REQUEST )

enter image description here


Solution

  • I think you are looking for this:

    from django_filters import rest_framework as filters
    
    class AppointmentFilter(django_filters.FilterSet):
          ref_code = filters.CharFilter(field_name="ref_code", required=True)
          expecting_time = filters.DateFilter(field_name="expecting_time", required=True)