Home > Software engineering >  Django-filter Choice Filter does not recognize an existing field
Django-filter Choice Filter does not recognize an existing field

Time:12-02

I am trying to appply a ChoiceFilter however it as if the field I am referring to is not recongized wherehas it does exist :

ModelViewsSet :

class StartUpViewSet(NestedViewSetMixin, ModelViewSet):
    """
      Class that provides List, Retrieve, Create, Update, Partial Update and Destroy  actions for startups.
      It also include a filter by startup status
    """
    model = Startup
    queryset = Startup.objects.all()
    serializer_class = StartupSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_fields = 'status'

FilterClass :

class StartupFilter(filters.FilterSet):
    status = filters.ChoiceFilter(choices=START_UP_STATUS)

    class Meta:
        model = Startup
        fields = ['status']

And model :

class Startup(models.Model):
    header = models.CharField("Header", max_length=255)
    title = models.CharField("Title", max_length=255)
    description = models.CharField("description", max_length=255)
    # TODO Change this to options instead of array
    tags = ArrayField(models.CharField(max_length=10, blank=True), size=5)
    # TODO Images to be stored in aws only url will be in DB
    card_image = models.ImageField(upload_to='media/images/cards')
    logo_image = models.ImageField(upload_to='media/images/logos')
    main_img = models.ImageField(upload_to='media/images/main', null=True)
    createdAt = models.DateTimeField("Created At", auto_now_add=True)
    status = models.IntegerField(choices=START_UP_STATUS, default=1)

    def __str__(self):
        return self.title

Error :

'Meta.fields' must not contain non-model field names: s, t, a, u

CodePudding user response:

As the name filtered_fields hints, it expects a collection of fields, not a single field. You thus should implement this as a list, tuple, set, or any other collection of strings, not a single string:

class StartUpViewSet(NestedViewSetMixin, ModelViewSet):
    # …
    filterset_fields = ('status',)

If you want to specify a custom FilterSet, you pass a reference to the class with:

class StartUpViewSet(NestedViewSetMixin, ModelViewSet):
    # no filterset_fields
    filterset_class = StartupFilter
  • Related