Creating a function-based filter with DjangoFilterBackend in DRF?

25 views
Skip to first unread message

Lucas Bracher

unread,
Feb 25, 2020, 4:14:29 AM2/25/20
to django-filter

TL;DR:

  - filter boolean field is_trashed from a model, using the input variable x

    - when x is False, return only records where is_trashed is False

    - when x is True, return all records


Hi there! :)


I have the following problem: I have a model called Products:


class Product(models.Model):
    label = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    type = models.CharField(
        max_length=50, choices=ProductType.choices())
    is_trashed = models.BooleanField(default=False)


And the viewset ProductViewSet:


class
ProductViewSet(GenericViewSet): serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend] filterset_fields = {"type": ("contains", "exact", "in"), "is_trashed": ("exact",)} search_fields = ["label"]


The problem is I would like to have a filter with a different behavior. When I pass false on is_trashed I only would like to retrieve those records which indeed is_trashed==False, but when I pass true, I would like to retrieve all records. The only way I can imagine doing that is using a function, but I'm clueless. How can I do that exactly?


Thanks in advance!


Lucas Bracher

Reply all
Reply to author
Forward
0 new messages