大家好,又见面了,我是你们的朋友全栈君。
1、视图
class UserView(ListAPIView):
"""用户列表"""
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (DjangoFilterBackend,)
filter_class = UserMonthFilter # 指定过滤类
2、过滤类
class RobotFilter(django_filters.FilterSet):
# 使用过滤:URL?created_start_time=2020_01-20&created_end_time=2020_01-21
robot_id = django_filters.CharFilter(field_name='id')
machine_id = django_filters.CharFilter(field_name='machine_id')
city = django_filters.CharFilter(field_name='city')
# lookup_expr(可选)为判断条件,field_name(必选)为模型类属性,created_time查询字符串
created_time= django_filters.CharFilter(field_name='created_at', lookup_expr='startswith')
created_start_time = django_filters.DateTimeFilter(field_name='created_at', lookup_expr='gt')
created_end_time = django_filters.DateTimeFilter(field_name='created_at', lookup_expr='lt')
problem_isnull = django_filters.BooleanFilter(field_name='problem', lookup_expr='isnull')
name = django_filters.CharFilter(lookup_expr='iexact') # iexact表示精确匹配, 并且忽略大小写
author = django_filters.CharFilter(lookup_expr='icontains') #icontains表示模糊查询(包含),并且忽略大小写
price = django_filters.NumberFilter(look_expr='exact') #exact表示精确匹配
task_res_state = django_filters.CharFilter(method="get_task_res_state")
def get_task_res_state(self, queryset, *arg):
if str(arg[1]) == "0": # arg[1]=('task_res_state', '0')
task_res = (1, 2, 3)
else:
task_res = (0, 4, 5, 6)
print(task_res)
queryset = queryset.filter(task_res__in=task_res)
return queryset
class Meta:
model = Robot
fields = ['robot_id', 'machine_id', "city", "created_start_time", "created_end_time", 'created_time',
'firmware_version', 'state', "robot_type", "hardware_version", "exist_map", 'task_res_state']
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/143578.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...