我有以下可选过滤器:
cat_id = self.request.GET.get('cat_id', '')
return Product.objects.filter(category__pk=cat_id)
当没有传递可选的cat_id时,我收到此错误:
ValueError at /api/products/
invalid literal for int() with base 10: ''
我的问题是,我如何做到这一点,以便当没有传递cat_id时,过滤器是这样的......
return Product.objects.filter()
或者有人可以向我展示更好的方法,如果我要包含10个可选过滤器会怎么样?
答案 0 :(得分:5)
这样的事可能吗?
filters = {}
cat_id = self.request.GET.get('cat_id', None)
if cat_id:
filters["category__pk"] = cat_id
return Product.objects.filter(**filters)
编辑:如果我有相当多的参数要过滤,我会尝试做这样的事情(未经测试):
# with all your possible lookups here
possible_filters = {"cat_id": "category__pk", "colour": "colour__pk", }
# and then go through the provided fields, and toggle the filters accordingly
enabled_filters = { possible_filters[filter]: self.request.GET[filter] for filter
in possible_filters
if self.request.GET.get(filter, None) }
return Product.objects.filter(**enabled_filters)