filters.py 2.07 KB
Newer Older
1
2
3
from datetime import datetime


okhin's avatar
okhin committed
4
from rest_framework.filters import BaseFilterBackend
5
6
from django.db.models import Q
from django.conf import settings
okhin's avatar
okhin committed
7
from django.utils.http import urlunquote
8

okhin's avatar
okhin committed
9

10
11
from .models import Mandate

okhin's avatar
okhin committed
12

13
14
15
16
class ActiveMandateQueryFilterBackend(BaseFilterBackend):
    """
    A filter which check if a mandate is active for a reprensentative

okhin's avatar
okhin committed
17
    the parameter used in the query to filter is, by default active_mandates
18
19
    and it list a list of mandates among which one should be active.
    """
okhin's avatar
okhin committed
20
    query_param = getattr(settings, 'ACTIVE_MANDATES_PARAM', 'active_mandates')
21
22
23
24
25
26

    def filter_queryset(self, request, queryset, view):
        qs = queryset

        if self.query_param in request.GET:
            if len(request.GET[self.query_param]):
okhin's avatar
okhin committed
27
                # We want to check for params in a list of mandates
okhin's avatar
okhin committed
28
                mandates = request.GET[self.query_param].split(',')
okhin's avatar
okhin committed
29
                qs = qs.filter(mandates__in=Mandate.objects.filter(
okhin's avatar
okhin committed
30
31
32
33
34
                    Q(end_date__gte=datetime.today) |
                    Q(end_date__isnull=True)).filter(
                        Q(group__name__in=mandates) |
                        Q(group__abbreviation__in=mandates)
                )).distinct()
okhin's avatar
okhin committed
35
36
        return qs

okhin's avatar
okhin committed
37

okhin's avatar
okhin committed
38
39
40
41
class ActiveConstituencyFilterBackend(BaseFilterBackend):
    """
    A filter which check if a representative is active in a constituency

okhin's avatar
okhin committed
42
43
    the parameter used in the query to filter is, by default,
    active_constituency.
okhin's avatar
okhin committed
44
    """
okhin's avatar
okhin committed
45
46
    query_param = getattr(settings,
            'ACTIVE_CONSTITUENCY_PARAM', 'active_constituency')
okhin's avatar
okhin committed
47
48
49
50
51

    def filter_queryset(self, request, queryset, view):
        qs = queryset

        if self.query_param in request.GET:
okhin's avatar
okhin committed
52
            if len(request.GET[self.query_param]):
okhin's avatar
okhin committed
53
                mandates = urlunquote(request.GET[self.query_param]).split(',')
okhin's avatar
okhin committed
54
55
56
                qs = qs.filter(mandates__in=Mandate.objects.filter(
                    Q(end_date__gte=datetime.today) |
                    Q(end_date__isnull=True)).filter(
okhin's avatar
okhin committed
57
                        Q(constituency__name__in=mandates)
okhin's avatar
okhin committed
58
                )).distinct()
59
        return qs