representative_detail.py 2.31 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 Representative, Address, Phone, WebSite
Jamesie Pic's avatar
Jamesie Pic committed
7
from representatives_positions.forms import PositionForm
8
from representatives_recommendations.models import VoteScore
9
from representatives_votes.models import Proposal
Jamesie Pic's avatar
Jamesie Pic committed
10

11
from .representative_mixin import RepresentativeViewMixin
Jamesie Pic's avatar
Jamesie Pic committed
12
13


14
class RepresentativeDetail(RepresentativeViewMixin, generic.DetailView):
Jamesie Pic's avatar
Jamesie Pic committed
15
16
17
18

    queryset = Representative.objects.select_related('score')

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

        qs = self.prefetch_for_representative_country_and_main_mandate(qs)

23
        social = ['twitter', 'facebook']
24
        qs = qs.prefetch_related(
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
            'email_set',
            models.Prefetch(
                'website_set',
                queryset=WebSite.objects.filter(kind__in=social),
                to_attr='social_websites'
            ),
            models.Prefetch(
                'website_set',
                queryset=WebSite.objects.exclude(kind__in=social),
                to_attr='other_websites'
            ),
            models.Prefetch(
                'address_set',
                queryset=Address.objects.select_related('country')
            ),
            models.Prefetch(
                'phone_set',
                queryset=Phone.objects.select_related('address__country')
            ),
            models.Prefetch(
                'votes',
                queryset=VoteScore.objects.filter(
                    proposal__in=Proposal.objects.exclude(recommendation=None),
48
49
                ).select_related('proposal__recommendation').order_by(
                    '-proposal__datetime')
50
51
            )
        )
52

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

    def get_context_data(self, **kwargs):
        c = super(RepresentativeDetail, self).get_context_data(**kwargs)
57
58
59
60
61
62
63
64

        self.add_representative_country_and_main_mandate(c['object'])

        c['votes'] = c['object'].votes.all()
        c['mandates'] = c['object'].mandates.all()
        c['positions'] = c['object'].positions.filter(
            published=True).prefetch_related('tags')

65
66
        c['position_form'] = PositionForm(
            initial={'representative': self.object.pk})
Jamesie Pic's avatar
Jamesie Pic committed
67
        self.add_representative_country_and_main_mandate(c['object'])
68

Jamesie Pic's avatar
Jamesie Pic committed
69
        return c