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"}]
name
从work
中基于j_field
或django-filter
过滤结果?import django_filters
class MyModelFilter(django_filters.FilterSet)
class Meta:
model = MyModel
...
...
what's next?
答案 0 :(得分:1)
基本上,您需要创建一个自定义方法进行过滤:
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)