如何过滤脱水过程中创建的自定义值?

时间:2014-02-10 08:06:34

标签: tastypie

在脱水期间,我创建了一个自定义值:

def dehydrate(self, bundle):
    bundle.data['custom_field'] = ["add lots of stuff and return an int"]
    return bundle

我想过滤。

/?format=json&custom_field__gt=0...

然而我收到了"[custom_field] field has no 'attribute' for searching with."

的错误

也许我误解了自定义过滤器,但build_filtersapply_filters我似乎无法访问自定义字段以对其进行过滤。在我看过的例子中,似乎我必须重做build_filters中脱水所做的所有工作,例如

for all the items:
    item['custom_field'] = ["add lots of stuff and return an int"]
    filter on item and add to pk_list 

orm_filters["pk__in"] = [i.pk for i in pk_list]

这似乎不对,因为我正在做两次工作。我错过了什么?

1 个答案:

答案 0 :(得分:1)

问题在于脱水是按设计“每个对象”,而过滤器是每个object_list。这就是为什么你必须手动过滤它并重做脱水工作。

你可以这样想象:

# Whole table
[obj, obj1, obj2, obj3, obj4, obj5, obj5]

# filter operations
[...]

# After filtering
[obj1, obj3, obj6]    

# Returning
[dehydrate(obj), dehydrate(obj3), dehydrate(obj5)] 

此外,你可以想象如果你通过过滤获取,你会说100个对象。在整个表上触发脱水(例如100000条记录)是非常低效的。

如果您计划使用大量过滤器,订购等,也许在模型中创建新列可能是候选解决方案。我想这个字段中的统计信息,如果不是新列那么可能django aggregation可能缓解你的痛苦。