如何在虚拟django模型字段(属性)上进行过滤?

时间:2013-12-24 10:44:03

标签: django tastypie

我有下一个django模型,其中tracker_id是一个虚拟字段:

class Failures(models.Model):
    _tracker_id = models.CharField('Tracker ID', max_length=50) 

    def __set_tracker_id(self, value):
        self._tracker_id = value

    def __get_tracker_id(self):
        issue = self.do_something(self._tracker_id)
        return issue

    tracker_id = property(__get_tracker_id, __set_tracker_id)

我也有tastypie资源:

class FailuresResource(BasicResource):
    tracker_id = fields.CharField(attribute='tracker_id')

    class Meta:
        queryset = Failures.objects.all()
        allowed_methods = ['get', 'post', 'put']

        filtering = {
            'tracker_id': ALL,
        }
        excludes = ('_tracker_id', )

BUT!当我尝试像tracker_id这样过滤对象时

http://myhost/api/v1/failures/?tracker_id=123

我收到错误:“无法将关键字'tracker_id'解析为字段。选项为:_tracker_id”

无论如何都要通过tracker_id进行过滤而不是内部字段???

谢谢!

1 个答案:

答案 0 :(得分:3)

通过Meta类过滤仅适用于实际字段。

尝试覆盖build_filters功能

def build_filters(self, filters=None):
    if filters is None:
        filters = {}

    orm_filters = super(FailuresResource, self).build_filters(filters)

    if 'tracker_id' in filters:
        # do your trick here
        orm_filters['_tracker_id'] = filters['tracker_id']

    return orm_filters

不要忘记在Meta课程中删除不工作的过滤器。