英文:
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 )
希望这可以帮助您。如果您有任何其他问题,请随时提出。
英文:
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 )
答案1
得分: 1
我认为您正在寻找这个:
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论