[英]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: 我可以使用波纹管链接来过滤
id=16
的数据:
http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id=16
this is my list api view: 这是我的列表api视图:
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? 我有一个问题,如何通过url查询
id>= 16
的数据列表?
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: 我知道我可以在ListAPIView查询中这样:
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: 您可以在视图中添加
filter_fields
属性,如下所示:
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: 为了实现这一点,你需要安装django-filter ,并将
DjangoFilterBackend
添加到你的settings.py
如果它还没有:
REST_FRAMEWORK = {
...
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
}
filter_fields
is commonly used with a list of model fields for exact lookups. filter_fields
通常与模型字段列表一起使用,以进行精确查找。 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
. 但是,也可以提供字典,如上例所示,它将模型字段映射到其他类型的查找 - 例如
gte
和lte
。
More information on the filter_fields
attribute can be found here . 有关
filter_fields
属性的更多信息,请参见此处 。 More information on the list/dict format of filter_fields
is here . 有关
filter_fields
的list / dict格式的更多信息,请点击此处 。
I would like to suggest django-url-filter
我想建议
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 同样,它适合您的上下文
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.