如何在DRF中使用django filter_fields和ArrayField

gupuwyp2  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(139)

我在模型中使用Postgres ArrayField。我正在尝试使用Django过滤器,但我得到了一个错误。
AutoFilterSet解析的字段“flavor”与“exact”查找为无法识别的字段类型ArrayField。尝试向“ meta.filter_overrides”添加覆盖。参见:https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides
型号

class Items(models.Model):
    item = models.CharField(max_length=150, unique=True)
    matches = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    category = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    flavor = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    special = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    created_at = models.DateTimeField(auto_now_add=True)

视图集

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Items.objects.all()
    serializer_class = CategorySerializer
    filter_fields = ('item', 'category')
bnl4lu3b

bnl4lu3b1#

我想出来了,哈哈。需要使用lookup_exp='icontains'创建自定义过滤器。

class CategoryFilter(filters.FilterSet):
    category = filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Items
        fields = ('item', 'category')
class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Items.objects.all()
    serializer_class = CategorySerializer
    filterset_class = CategoryFilter
piztneat

piztneat2#

如果你想为ArrayField实现一些特定的查找,试试这个:

from django.contrib.postgres.forms.array import SimpleArrayField
from django_filters.filters import Filter

class ArrayOverlapFilter(Filter):
    field_class = SimpleArrayField

  def __init__(self, *args, **kwargs):
      kwargs.setdefault("lookup_expr", "overlap")
      super().__init__(*args, **kwargs)

在FilterSet中定义时,必须指定base_field:

devices = ArrayOverlapFilter(base_field=CharField())

相关问题