我正在使用带有django-filter的django-rest-framework来实现过滤。 假设我有以下结果:
{
"id": 13,
"created": "2017-06-21T01:08:49.790254Z",
"updated": "2017-07-21T10:25:51.706730Z",
"toylist": [],
}
如何实现过滤,以便检查toylist数组是否为空?例如,类似于:/toys/?toylist__isnull=True
答案 0 :(得分:0)
好的,这是一个相对简单的修复:
class ToysFilter(filters.FilterSet):
toylist__isnull = filters.BooleanFilter(name='toylist', method='list_is_empty')
class Meta:
model = Toys
fields = {
'id':['exact'],
'created':'__all__',
'updated':'__all__',
}
def list_is_empty(self, qs, name, value):
isnull = not value
lookup_expr = LOOKUP_SEP.join([name, 'isnull'])
return qs.filter(**{lookup_expr: isnull}).distinct()
答案 1 :(得分:0)
在此处使用方法并不是必需的。更简单地说,您可以执行以下操作:
class ToysFilter(filters.FilterSet):
toylist__isnull = filters.BooleanFilter(name='toylist', lookup_expr='isnull', distinct=True)