filters.py 1.04 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
19
20
21
22
23
24
25
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.
    """
    query_param = getattr(settings, 'ACTIVE_MANDATES_QUERY_PARAM', 'active_mandates')

    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
28
                qs = qs.filter(mandates__in=Mandate.objects.filter(Q(end_date__gte=datetime.today)
                    | Q(end_date__isnull=True)).filter(Q(group__name=request.GET[self.query_param])
                        | Q(group__abbreviation=request.GET[self.query_param]))).distinct()
29
30
                return qs
        return qs