representative_list.py 2.09 KB
Newer Older
1
2
# coding: utf-8

3
from core.views import GridListMixin, PaginationMixin, CSVDownloadMixin, \
4
    ActiveLegislatureMixin, SortMixin
5
6
7

from django.views import generic

8
from representatives.models import Representative
9

10
from ..filters import RepresentativeFilter
11
12
from .representative_mixin import RepresentativeViewMixin

Nicolas Joyard's avatar
Nicolas Joyard committed
13
14
from representatives_positions.views import PositionFormMixin

15
16

class RepresentativeList(CSVDownloadMixin, GridListMixin, PaginationMixin,
17
                         RepresentativeViewMixin, ActiveLegislatureMixin,
Nicolas Joyard's avatar
Nicolas Joyard committed
18
                         SortMixin, PositionFormMixin, generic.ListView):
19

20
    csv_name = 'representatives'
21
    queryset = Representative.objects.select_related('score')
22
    current_filter = None
23
24
25
26
27
    sort_fields = {
        'last_name': 'name',
        'score__score': 'score',
    }
    sort_default_field = 'last_name'
28
29
30
31

    def get_context_data(self, **kwargs):
        c = super(RepresentativeList, self).get_context_data(**kwargs)

32
        c['filter'] = self.current_filter
33
        c['view'] = 'representative_list'
34
35
36
37
38
39
40
        c['object_list'] = [
            self.add_representative_country_and_main_mandate(r)
            for r in c['object_list']
        ]

        return c

41
42
43
44
    def rep_filter(self, qs):
        f = RepresentativeFilter(self.request.GET, queryset=qs)
        self.current_filter = f
        return f.qs
45
46
47

    def get_queryset(self):
        qs = super(RepresentativeList, self).get_queryset()
48
49
        if self.get_active_only():
            qs = qs.filter(active=True)
50
        qs = self.rep_filter(qs)
51
        qs = self.prefetch_for_representative_country_and_main_mandate(qs)
52
        return qs.distinct()
53
54

    def get_csv_results(self, context, **kwargs):
55
        qs = self.get_queryset()
56
57
58
59
60
61
62
63
        qs = qs.prefetch_related('email_set')
        return [self.add_representative_country_and_main_mandate(r)
                for r in qs]

    def get_csv_row(self, obj):
        return (
            obj.full_name,
            u', '.join([e.email for e in obj.email_set.all()]),
Nicolas Joyard's avatar
Nicolas Joyard committed
64
            obj.main_mandate.group.abbreviation if obj.main_mandate else None,
65
66
            obj.country,
        )