Created
June 8, 2017 19:02
-
-
Save gepatino/a7a2bcefce858b6e79577c22266b97eb to your computer and use it in GitHub Desktop.
Filter to allow multiple options in Char filters for DRF + django_filters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import django_filters | |
class MultipleCharFilter(django_filters.CharFilter): | |
""" | |
Allows multiple options in a comma separated list for Char fields. | |
Example: | |
- field=value # filter by a single value | |
- field=val1,val2 # Filter by val1 OR val2 (Django's 'in' lookup) | |
""" | |
def filter(self, qs, value): | |
if not value: | |
return qs | |
values = value.split(',') | |
if len(values) > 1: | |
self.lookup_expr = 'in' | |
else: | |
values = values[0] | |
return super(MultipleCharFilter, self).filter(qs, values) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment