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
现在根据要求,我们必须创建一个过滤器,该过滤器将导致[XXXXXX,YYYYY]中的所有设备(uuid + major + minor)
我已经通过了
中提到的提前过滤器了
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方法。
答案 0 :(得分:0)
我会尝试使用注释:
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