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


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

okhin's avatar
okhin committed
8

9 10
from .models import Mandate

okhin's avatar
okhin committed
11

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

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

    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
26
                # We want to check for params in a list of mandates
okhin's avatar
okhin committed
27
                mandates = request.GET[self.query_param].split(',')
okhin's avatar
okhin committed
28
                qs = qs.filter(mandates__in=Mandate.objects.filter(
okhin's avatar
okhin committed
29 30 31 32 33
                    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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
        return qs

class ActiveConstituencyFilterBackend(BaseFilterBackend):
    """
    A filter which check if a representative is active in a constituency

    the parameter used in the query to filter is, by default, active_constituency.
    """
    query_param = getattr(settings, 'ACTIVE_CONSTITUENCY_PARAM', 'active_constituency')

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

        if self.query_param in request.GET:
            if len(request.GET[self.query_params]):
                mandates = request.GET[self.query_param].split(',')
                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
53
                        Q(constituency__name__in=mandates)
okhin's avatar
okhin committed
54
                )).distinct()
55
        return qs