在DRF中将Both Value设置为django_filters的条件,如果条件为空则显示自定义错误

e4eetjau  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(195)

我正在尝试使用Django Restful Framework中的Filter使用django_filters。我想使用两个字段,因此这两个字段都必须满足条件。这意味着用户必须输入ref_code和expecting_time。但是现在,如果用户输入ref_code,查询仍然有效。最后,如果查询为空,我需要一个自定义的消息。
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

hfyxw5xn

hfyxw5xn1#

我想你在找这个:

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)

相关问题