filters.py 1.58 KB
Newer Older
1
2
# coding: utf-8

3
4
5
6
7
from dal.autocomplete import ModelSelect2

import datetime

from django.db.models import Q
8
9
10
11
12
13
14
15
from django.utils.text import slugify

from django_filters import FilterSet, MethodFilter, ModelChoiceFilter

from representatives.models import Chamber, Group, Representative


def chamber_filter(qs, value):
16
17
18
19
20
    today = datetime.date.today()
    return qs.filter(
        Q(mandates__end_date__gte=today) | Q(mandates__end_date__isnull=True),
        mandates__group__chamber=value
    )
21
22
23


def group_filter(qs, value):
24
25
26
27
28
    today = datetime.date.today()
    return qs.filter(
        Q(mandates__end_date__gte=today) | Q(mandates__end_date__isnull=True),
        mandates__group=value
    )
29
30
31
32
33
34
35
36
37
38
39
40


class RepresentativeFilter(FilterSet):

    search = MethodFilter(action='search_filter')

    chamber = ModelChoiceFilter(queryset=Chamber.objects.all(),
                                action=chamber_filter)

    country = ModelChoiceFilter(queryset=Group.objects.filter(kind='country'),
                                action=group_filter)

41
42
43
44
45
46
    group = ModelChoiceFilter(queryset=Group.objects.exclude(
                              kind__in=['chamber', 'country']),
                              action=group_filter,
                              widget=ModelSelect2(url='group-autocomplete'),
                              label='Party, committee or delegation')

47
48
49
50
51
52
53
54
55
    class Meta:
        model = Representative
        fields = ['search', 'chamber', 'country']

    def search_filter(self, qs, value):
        if len(value) == 0:
            return qs

        return qs.filter(slug__icontains=slugify(value))