如何在JSONField上使用django过滤器



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-filterj_field筛选基于namework的结果
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)

相关内容

  • 没有找到相关文章

最新更新