如何在JSONField

时间:2019-11-21 14:57:54

标签: django django-models django-rest-framework django-forms django-templates

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"}]
  • 如何使用namework中基于j_fielddjango-filter过滤结果?
import django_filters

class MyModelFilter(django_filters.FilterSet)
  class Meta:
      model = MyModel 
        ...
        ...
        what's next?

1 个答案:

答案 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)