1

按照此处提供的示例: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 是一个字典映射而不是一个列表。因此,我收到错误:

"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 方法在从 apply_filters 中获取“自定义”后将其删除。

不确定我的 apply_filters def 有什么问题。

4

1 回答 1

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
于 2012-07-31T09:05:50.427 回答