filters.py 2.2 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
from django.utils.text import slugify

from django_filters import FilterSet, MethodFilter, ModelChoiceFilter

from representatives.models import Chamber, Group, Representative
Nicolas Joyard's avatar
Nicolas Joyard committed
13
from representatives_votes.models import Dossier
14
15


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


24
25
26
27
def dossier_chamber_filter(qs, value):
    return qs.filter(documents__chamber=value)


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


class RepresentativeFilter(FilterSet):

    search = MethodFilter(action='search_filter')

    chamber = ModelChoiceFilter(queryset=Chamber.objects.all(),
41
                                action=rep_chamber_filter)
42
43
44
45

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

46
47
48
49
50
51
    group = ModelChoiceFilter(queryset=Group.objects.exclude(
                              kind__in=['chamber', 'country']),
                              action=group_filter,
                              widget=ModelSelect2(url='group-autocomplete'),
                              label='Party, committee or delegation')

52
53
54
55
56
57
58
59
60
    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))
Nicolas Joyard's avatar
Nicolas Joyard committed
61
62
63
64
65
66


class DossierFilter(FilterSet):

    search = MethodFilter(action='search_filter')

67
68
69
    chamber = ModelChoiceFilter(queryset=Chamber.objects.all(),
                                action=dossier_chamber_filter)

Nicolas Joyard's avatar
Nicolas Joyard committed
70
71
    class Meta:
        model = Dossier
72
        fields = ['search', 'chamber']
Nicolas Joyard's avatar
Nicolas Joyard committed
73
74
75
76
77
78
79

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

        return qs.filter(Q(title__icontains=value) |
                         Q(reference__icontains=value))