Reputation: 3569
I can use the bellow link to filter the id=16
's data:
http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id=16
this is my list api view:
class PhysicalServerTaskListAPIView(ListAPIView):
serializer_class = PhysicalServerTaskListSerializer
permission_classes = [IsAdminUser]
def get_queryset(self):
query_params = self.request.query_params
filters = {'{}__contains'.format(key): value
for key, value in query_params.items()
}
return PhysicalServerTask.objects.filter(**filters)
I have a question, how can I query the id>= 16
's data list through the url?
I mean whether I can through the:
http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id__gte=16
to filter the data.
I know I can in the ListAPIView query like this:
id_gte = self.request.query_params.copy().get('id_gte')
...
qs = PhysicalServerTask.objects.filter(**filters)
qs.filter(Q(id__gte=id__gte))
but whether there is a more convenient way to realize this?
Upvotes: 7
Views: 10462
Reputation: 23004
You can add a filter_fields
attribute to your view like this:
class PhysicalServerTaskListAPIView(ListAPIView):
...
filter_fields = {
'id': ['gte', 'lte']
}
That will allow you to make queries such as:
http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id__gte=16
http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id__lte=16
For that to work, you will need to install django-filter, and add the DjangoFilterBackend
to your settings.py
if it is not already there:
REST_FRAMEWORK = {
...
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
filter_fields
is commonly used with a list of model fields for exact lookups. However, a dictionary can also be supplied, like in the example above, which maps model fields to other types of lookups - such as gte
and lte
.
More information on the filter_fields
attribute can be found here. More information on the list/dict format of filter_fields
is here.
Upvotes: 22