models 列表视图的字段查询封装
This commit is contained in:
parent
34511da090
commit
eb90c17711
|
@ -62,9 +62,6 @@ class ModelViewBase(Resource):
|
|||
except:
|
||||
abort(404, msg=f"resource '{pk}' not found")
|
||||
|
||||
def get_queryset(self):
|
||||
return self.model.objects
|
||||
|
||||
def paginate_queryset(self, queryset):
|
||||
"""分页: https://${URL}/?page=1&limit=15"""
|
||||
# 分页参数
|
||||
|
@ -158,6 +155,38 @@ class ModelViewBase(Resource):
|
|||
|
||||
class ListMixin(ModelViewBase):
|
||||
|
||||
# filter 过滤的字段参数
|
||||
filter_fields = []
|
||||
|
||||
def get_queryset(self):
|
||||
"""简单的过滤,默认操作符为等于"""
|
||||
query_params = {}
|
||||
# 搜索字段必须在模型对象中
|
||||
all_fields = self.model._fields
|
||||
# 遍历视图定义的过滤字段集合
|
||||
for arg, operators in self.filter_fields:
|
||||
# 过滤参数不在字段列表中
|
||||
if arg not in all_fields:
|
||||
continue
|
||||
# get传递的参数值为空或不存在,忽略
|
||||
val = request.args.get(arg, "")
|
||||
if not val:
|
||||
continue
|
||||
# 查询运算符,若为空则默认是等于
|
||||
if operators:
|
||||
query_params[f"{arg}__{operators}"] = val
|
||||
else:
|
||||
query_params[f"{arg}"] = val
|
||||
|
||||
try:
|
||||
# 字段值异常会抛错
|
||||
queryset = self.model.objects(**query_params)
|
||||
except:
|
||||
# 返回空 queryset
|
||||
queryset = self.model.objects.none()
|
||||
app.logger.exception(f"查询出错 {self.model} query_params={query_params}")
|
||||
return queryset
|
||||
|
||||
def get(self):
|
||||
"""获取列表数据"""
|
||||
# 过滤后的数据,
|
||||
|
|
Loading…
Reference in New Issue