Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an initial/default value using Django Filters?

Tags:

python

django

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.

like image 411
Prometheus Avatar asked Oct 03 '16 14:10

Prometheus


People also ask

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

Can you filter by property Django?

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.


1 Answers

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

like image 85
Ilya Petukhov Avatar answered Sep 19 '22 21:09

Ilya Petukhov