django-filter
在Model的所有默认字段上都能很好地工作,但当我们想在JSONField 等postgres字段上工作时,问题就来了
我有以下型号:
from django.contrib.postgres.fields import JSONField,ArrayField
class MyModel(models.Model):
j_field = JSONField(blank=True,null=True,default=dict)
j_field
具有以下结构的数据:
[{"name":"john","work":"developer"},{"name":"cena","work":"teacher"}]
- 如何使用
django-filter
从j_field
筛选基于name
或work
的结果
import django_filters
class MyModelFilter(django_filters.FilterSet)
class Meta:
model = MyModel
...
...
what's next?
基本上,您需要创建一个自定义方法来过滤:
import django_filters
class MyModelFilter(django_filters.FilterSet)
class Meta:
model = MyModel
fields = ('name', 'work')
name = django_filters.CharFilter(
method='name_filter'
)
work = django_filters.CharFilter(
method='work_filter'
)
def name_filter(self, queryset, name, value):
return queryset.filter(j_field__name__iexact=value)
def work_filter(self, queryset, name, value):
return queryset.filter(j_field__work__iexact=value)