Skip to content

Instantly share code, notes, and snippets.

@gepatino
Created June 8, 2017 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gepatino/a7a2bcefce858b6e79577c22266b97eb to your computer and use it in GitHub Desktop.
Save gepatino/a7a2bcefce858b6e79577c22266b97eb to your computer and use it in GitHub Desktop.
Filter to allow multiple options in Char filters for DRF + django_filters
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