Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use django filter_fields with ArrayField in DRF

I am using a Postgres ArrayField in my models. I am trying to use django filters but I get an error for them.

AutoFilterSet resolved field 'flavor' with 'exact' lookup to an unrecognized field type ArrayField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides

Model

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)

ViewSet

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Items.objects.all()
    serializer_class = CategorySerializer
    filter_fields = ('item', 'category')
like image 747
Eat_ Mangos Avatar asked May 22 '19 08:05

Eat_ Mangos


1 Answers

Well I figured it out, lol. Needed to create a custom filter with 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
like image 122
Eat_ Mangos Avatar answered Nov 16 '22 17:11

Eat_ Mangos