So many things get better/are improved, but only things that are to be done or broken...
[wolnelektury.git] / apps / polls / models.py
1 from django.db import models
2 from django.utils.translation import ugettext_lazy as _
3 from django.core.exceptions import ValidationError
4 from django.core.urlresolvers import reverse
5
6
7 USED_POLLS_KEY = 'used_polls'
8
9
10 class Poll(models.Model):
11
12     question = models.TextField(_('question'))
13     slug = models.SlugField(_('slug'))
14     open = models.BooleanField(_('open'), default = False)
15     
16     class Meta:
17         verbose_name = _('Poll')
18         verbose_name_plural = _('Polls')
19     
20     def clean(self):
21         if self.open and Poll.objects.exclude(pk = self.pk).filter(slug = self.slug).exists():
22             raise ValidationError(_('Slug of an open poll needs to be unique'))
23         return super(Poll, self).clean()
24         
25     def __unicode__(self):
26         return self.question[:100] + ' (' + self.slug + ')'
27         
28     def get_absolute_url(self):
29         return reverse('poll', args = [self.slug])
30         
31     @property
32     def vote_count(self):
33         return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum']
34         
35     def voted(self, session):
36         return self.id in session.get(USED_POLLS_KEY, set())
37
38         
39 class PollItem(models.Model):
40     
41     poll = models.ForeignKey(Poll, related_name = 'items')
42     content = models.TextField(_('content'))
43     vote_count = models.IntegerField(_('vote count'), default = 0)
44     
45     class Meta:
46         verbose_name = _('vote item')
47         verbose_name_plural = _('vote items')
48         \r
49     def __unicode__(self):
50         return self.content + ' @ ' + unicode(self.poll)
51     
52     @property
53     def vote_ratio(self):
54         return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0
55         
56     def vote(self, session):
57         self.vote_count = self.vote_count + 1
58         self.save()
59         session.setdefault(USED_POLLS_KEY, set()).add(self.poll.id)
60         session.save()