【问题标题】:How to make filtering in tastypie on virtual django model field (property)?如何在虚拟 django 模型字段(属性)上的美味派中进行过滤?
【发布时间】:2014-01-12 14:40:39
【问题描述】:

我有下一个 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)

我也有美味的资源:

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', )

但是!当我尝试像这样通过 tracker_id 过滤对象时

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

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

有没有办法通过tracker_id而不是内部字段进行过滤???

谢谢!

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    通过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 类中不起作用的过滤器。

    【讨论】:

    • 谢谢。我也是这么想的。但在我的情况下,最好覆盖 apply_filters 而不是 build_filters。将 build_filters 与从 ModelResource 继承的 Resource 一起使用会遇到麻烦
    • @adityasdarma1,很好的答案
    猜你喜欢
    • 2014-03-15
    • 2012-10-30
    • 2014-07-03
    • 1970-01-01
    • 2012-02-23
    • 2011-09-13
    • 2019-09-19
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多