【问题标题】:Tastypie: Advance filter with complex queryTastypie:具有复杂查询的高级过滤器
【发布时间】:2016-04-12 15:27:19
【问题描述】:
model.py
class Device(models.Model):
    uuid = models.CharField(max_length=100)
    major = models.CharField(max_length=10)
    minor = models.CharField(max_length=10)

resource.py
class DeviceResourceV3(ModelResource):
    '''Fetch device details'''
    class Meta:
        queryset = Device.objects.all()
        resource_name = 'device'
        always_return_data = True
        filtering = {
            'uuid': ['exact', 'in'],
            'id': ['exact']
    }

请求的 API 调用:

/api/device?uuidmm__in=XXXXXX,YYYYY

现在根据要求,我们必须创建一个过滤器,它将导致所有设备(uuid + major + minor)在 [XXXXXX,YYYYY]

我已经了解了

http://django-tastypie.readthedocs.org/en/latest/resources.html
Django Tastypie Advanced Filtering: How to do complex lookups with Q objects

中提到的高级过滤器,但是这个特殊的用例变得太复杂了。任何人都可以为此查询建议适当的 build_filters 和 apply_filters 方法,或任何其他简单的方法。

【问题讨论】:

    标签: python django python-2.7 tastypie


    【解决方案1】:

    我会尝试使用注释:

    class DeviceResourceV3(ModelResource):
        uuidmm = fields.CharField(max_length=120)
    
    
        class Meta:
            queryset = Device.objects.all().annotate(uuidmm=(Concat('uuid', 'major', 'minor'))),
            resource_name = 'device'
            always_return_data = True
            filtering = {
                'uuid': ['exact', 'in'],
                'id': ['exact'],
                'uuidmm': ['exact', 'in']
        }
    

    如果“__in”可以使用这种方法,我现在无法测试它。如果没有,你也可以覆盖apply_filters

    def apply_filters(self, request, applicable_filters):
        semi_filtered = super(DeviceResourceV3, self).apply_filters(request, applicable_filters)
    
        uuidmms = request.GET.get('uuidmm__in', None)
    
        if uuidmms:
            # handle your filtering here, e.g. by combining all uuidmms to one string and check, and exclude the ones that are not in the combined string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-18
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多