简体   繁体   中英

How to filter the data use equal or greater than condition in the url?

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?

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 .

I would like to suggest django-url-filter

From the doc, it says

# get user who joined in after 2010 as per user profile
example.com/users/?profile__joined__gt=2010-01-01<br>

Similarly, it will suit in your context

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM