From 5fc2da48b304fe78a6c0139e4bf46f2dd34571a6 Mon Sep 17 00:00:00 2001 From: okhin Date: Thu, 12 Jan 2017 18:18:57 +0100 Subject: [PATCH] FIX #184: Add a active_mandates= filter on queries --- src/representatives/api.py | 5 ++++- src/representatives/filters.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/representatives/filters.py diff --git a/src/representatives/api.py b/src/representatives/api.py index c6fb280..ab00c78 100644 --- a/src/representatives/api.py +++ b/src/representatives/api.py @@ -32,6 +32,8 @@ from .models import ( WebSite, ) +from .filters import ActiveMandateQueryFilterBackend + class DefaultWebPagination(pagination.PageNumberPagination): default_web_page_size = 10 @@ -56,7 +58,8 @@ class RepresentativeViewSet(viewsets.ReadOnlyModelViewSet): filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, - RQLFilterBackend + RQLFilterBackend, + ActiveMandateQueryFilterBackend ) filter_fields = { 'active': ['exact'], diff --git a/src/representatives/filters.py b/src/representatives/filters.py new file mode 100644 index 0000000..925dac7 --- /dev/null +++ b/src/representatives/filters.py @@ -0,0 +1,28 @@ +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)) + .filter(Q(group__name=request.GET[self.query_param]))).distinct() + return qs + return qs -- GitLab