Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to conditionally require a field in a Django Filterset?

Let's say I have a Filterset:

class AnimalFilter(filters.FilterSet):
     animal_family = filters.CharFilter(required=True)
     is_land_animal = filters.BooleanFilter(required=True)

But what if I only want to set required=True for one or the other. Like if someone passes in animal_family, I don't need to receive is_land_animal or vise versa.

like image 210
Pittfall Avatar asked Sep 03 '25 02:09

Pittfall


1 Answers

You may have to use something undocumented(?). If you look at the source of django-filters you will see that in __init__ it binds your view's request to self.request.

You can therefore code these filters using method= and supply method code to peek in self.request.GET when the method gets invoked to see whether the "other" one has been supplied. If so, leave the queryset unmodified.

Both filters required=False. If you are determined to prevent neither being supplied, you'd need to check somewhere (in your view's get method?) that one or other is in request.GET and raise an exception or redirect to an error-view.

All off the top of my head while waiting for a quarter-Terabyte to copy.

like image 128
nigel222 Avatar answered Sep 05 '25 23:09

nigel222