How can I add an initial/default value when using Django Filters?
For example, something like this initial=False
class UserFilter(django_filters.FilterSet):
archive = django_filters.BooleanFilter(initial=False)
class Meta:
model = User
fields = ['archive']
I've tired to override the __init__
but this does not appear to work.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.
For DRF you can try override __init__
:
def __init__(self, *args, **kwargs):
kwargs['data']._mutable = True
if 'archive' not in kwargs['data']:
kwargs['data']['archive'] = False
kwargs['data']._mutable = False
super(UserFilter, self).__init__(*args, **kwargs)
But you should read django-filter.readthedocs.io...using-initial-values-as-defaults
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With