filters.py 1.08 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from datetime import datetime

from rest_framework.filters import BaseFilterBackend

from django.db.models import Q
from django.conf import settings

from .models import Mandate

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