From ca0489ec5814687670b1b717a2e059bcae1fc59c Mon Sep 17 00:00:00 2001 From: okhin Date: Thu, 9 Feb 2017 17:25:10 +0100 Subject: [PATCH] Create the active_constituency --- src/representatives/api.py | 7 ++++--- src/representatives/filters.py | 24 ++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/representatives/api.py b/src/representatives/api.py index ab00c78..347ff4e 100644 --- a/src/representatives/api.py +++ b/src/representatives/api.py @@ -32,8 +32,8 @@ from .models import ( WebSite, ) -from .filters import ActiveMandateQueryFilterBackend - +from .filters import (ActiveMandateQueryFilterBackend, + ActiveConstituencyFilterBackend) class DefaultWebPagination(pagination.PageNumberPagination): default_web_page_size = 10 @@ -59,7 +59,8 @@ class RepresentativeViewSet(viewsets.ReadOnlyModelViewSet): filters.SearchFilter, filters.OrderingFilter, RQLFilterBackend, - ActiveMandateQueryFilterBackend + ActiveMandateQueryFilterBackend, + ActiveConstituencyFilterBackend ) filter_fields = { 'active': ['exact'], diff --git a/src/representatives/filters.py b/src/representatives/filters.py index 70a0616..216b022 100644 --- a/src/representatives/filters.py +++ b/src/representatives/filters.py @@ -13,7 +13,7 @@ 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 + the parameter used in the query to filter is, by default active_mandates and it list a list of mandates among which one should be active. """ query_param = getattr(settings, 'ACTIVE_MANDATES_PARAM', 'active_mandates') @@ -31,5 +31,25 @@ class ActiveMandateQueryFilterBackend(BaseFilterBackend): Q(group__name__in=mandates) | Q(group__abbreviation__in=mandates) )).distinct() - return qs + 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( + Q(constituency__name__in=mandates + )).distinct() return qs -- GitLab