filters.py 1.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
16
17
18
class ActiveMandateQueryFilterBackend(BaseFilterBackend):
    """
    A filter which check if a mandate is active for a reprensentative

    the parameter used in the query to filter is, by default mandates_active
    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
27
                # We want to check for params in a list of mandates
                mandates = request.GET[self.query_params].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()
34
35
                return qs
        return qs