representative_detail_base.py 1.96 KB
Newer Older
1
2
# coding: utf-8

Jamesie Pic's avatar
Jamesie Pic committed
3
from django.db import models
4
from django.views import generic
Jamesie Pic's avatar
Jamesie Pic committed
5

6
from representatives.models import Chamber, Representative, Phone, WebSite
Jamesie Pic's avatar
Jamesie Pic committed
7

8
from .representative_mixin import RepresentativeViewMixin
Jamesie Pic's avatar
Jamesie Pic committed
9

Nicolas Joyard's avatar
Nicolas Joyard committed
10
from representatives_positions.views import PositionFormMixin
Jamesie Pic's avatar
Jamesie Pic committed
11

Nicolas Joyard's avatar
Nicolas Joyard committed
12
13
14

class RepresentativeDetailBase(RepresentativeViewMixin, PositionFormMixin,
                               generic.DetailView):
Jamesie Pic's avatar
Jamesie Pic committed
15

16
    queryset = Representative.objects.select_related('representative_score')
Jamesie Pic's avatar
Jamesie Pic committed
17
18

    def get_queryset(self):
19
        qs = super(RepresentativeDetailBase, self).get_queryset()
20
21
22

        qs = self.prefetch_for_representative_country_and_main_mandate(qs)

23
        social = ['twitter', 'facebook']
24
25
26
        chambers = [c['abbreviation']
                    for c in Chamber.objects.values('abbreviation')]

27
        qs = qs.prefetch_related(
28
29
30
31
32
33
34
35
            'email_set',
            models.Prefetch(
                'website_set',
                queryset=WebSite.objects.filter(kind__in=social),
                to_attr='social_websites'
            ),
            models.Prefetch(
                'website_set',
36
37
38
39
40
41
42
                queryset=WebSite.objects.filter(kind__in=chambers),
                to_attr='chamber_websites'
            ),
            models.Prefetch(
                'website_set',
                queryset=WebSite.objects.exclude(kind__in=social)
                                .exclude(kind__in=chambers),
43
44
                to_attr='other_websites'
            ),
45
46
            'address_set__country',
            'address_set__phones',
47
48
            models.Prefetch(
                'phone_set',
49
                queryset=Phone.objects.filter(address__isnull=True)
50
51
            )
        )
52

Jamesie Pic's avatar
Jamesie Pic committed
53
54
55
        return qs

    def get_context_data(self, **kwargs):
56
        c = super(RepresentativeDetailBase, self).get_context_data(**kwargs)
57

Jamesie Pic's avatar
Jamesie Pic committed
58
        self.add_representative_country_and_main_mandate(c['object'])
Nicolas Joyard's avatar
Nicolas Joyard committed
59
        c['position_form'].fields['representative'].initial = c['object'].pk
60

Jamesie Pic's avatar
Jamesie Pic committed
61
        return c