按照此处提供的示例:https://stackoverflow.com/a/10022244/1386588我遇到了提供示例代码的问题。
我有以下高级过滤器定义:
def build_filters(self, filters=None):
if filters is None:
filters = {}
orm_filters = super(TaggedResource, self).build_filters(filters)
if('query' in filters):
query = filters['query']
print query
qset = (
Q(comment__icontains=query) |
Q(media_text__icontains=query)
)
orm_filters.extend({'custom': qset})
我遇到的问题是orm_filters是一个dict映射而不是列表。因此,我收到错误:
"error_message": "'dict' object has no attribute 'extend'"
如果我尝试添加键和值对,就像我使用常规dict对象一样:
orm_filters['custom'] = qset
我在添加“自定义”键后尝试return orm_filters
时收到以下错误:
"error_message": "Cannot resolve keyword 'custom' into field. Choices are: comment, id, media_text, ..."
知道我做错了什么?
我一直试图找到解决方案一段时间没有任何运气,在此提前感谢您的帮助!
更新:我认为问题是我尝试覆盖apply_filters并未实例化:
def apply_filters(self, request, applicable_filters):
print 'applied filters'
if 'custom' in applicable_filters:
custom = applicable_filters.pop('custom')
else:
custom = None
semi_filtered = super(TaggedResource, self).apply_filters(request, applicable_filters)
return semi_filtered.filter(custom) if custom else semi_filtered
这可能是我无法解决关键字“自定义”错误的原因,因为我希望此处的apply_filters方法在从applicable_filters中获取后删除“自定义”。
不确定我的apply_filters def。
有什么问题答案 0 :(得分:1)
尝试改变:
orm_filters.extend({'custom': qset})
为:
orm_filters.update(**qset)
更新(经过测试的代码)
def build_filters(self, filters=None):
filters = filters
applicable_filters = super(TaggedResource, self).build_filters(filters)
query = filters.get('query')
if query:
qset = (
Q(comment__icontains=query) |
Q(media_text__icontains=query)
)
applicable_filters['custom'] = qset
return applicable_filters
def apply_filters(self, request, applicable_filters):
custom = None
if 'custom' in applicable_filters:
custom = applicable_filters.pop('custom')
semi_filtered = super(TaggedResource, self).apply_filters(request, applicable_filters)
return semi_filtered.filter(**custom) if custom else semi_filtered