class CompanyLanguageFilter(django_filters.FilterSet):
language__name = django_filters.CharFilter(label='Language', lookup_expr='icontains',)
group__name = django_filters.CharFilter(label='Group', lookup_expr='icontains',)
class Meta:
model = CompanyLanguage
fields = fields = {
}
Ordering
CHOICES = (
('ascending', 'Ascending'),
('desending', 'Descending')
)
ordering = django_filters.ChoiceFilter(label='Ordering', choices=CHOICES, method='filter_by_order')
def filter_by_order(self, queryset, name, value):
expression = 'language__name' if value == 'ascending' else '-language__name'
return queryset.order_by(expression)
Resource:
https://www.youtube.com/watch?v=nle3u6Ww6Xk&t=3s
Official example:
https://django-filter.readthedocs.io/en/stable/ref/filters.html#orderingfilter
class UserFilter(FilterSet):
account = CharFilter(field_name='username')
status = NumberFilter(field_name='status')
o = OrderingFilter(
Tuple-mapping retains order
fields=(
('username', 'account'),
('first_name', 'first_name'),
('last_name', 'last_name'),
),
Labels do not need to retain order
field_labels={
'username': 'User account',
}
)
class Meta:
model = User
fields = ['first_name', 'last_name']
>>> UserFilter().filters['o'].field.choices
[
('account', 'User account'),
('-account', 'User account (descending)'),
('first_name', 'First name'),
('-first_name', 'First name (descending)'),
('last_name', 'Last name'),
('-last_name', 'Last name (descending)'),
]