comparison gpp/polls/models.py @ 1:dbd703f7d63a

Initial import of sg101 stuff from private repository.
author gremmie
date Mon, 06 Apr 2009 02:43:12 +0000
parents
children cb121a3abf46
comparison
equal deleted inserted replaced
0:900ba3c7b765 1:dbd703f7d63a
1 '''
2 Models for the Polls application.
3 '''
4
5 import datetime
6 from django.db import models
7 from django.db.models import Q
8
9
10 class PollManager(models.Manager):
11 """Manager for the Poll model"""
12
13 def get_current_polls(self):
14 now = datetime.datetime.now()
15 return self.filter(
16 Q(is_enabled=True),
17 Q(start_date__lte=now),
18 Q(end_date__isnull=True) | Q(end_date__gte=now))
19
20 def get_old_polls(self):
21 now = datetime.datetime.now()
22 return self.filter(
23 Q(is_enabled=True),
24 Q(end_date__isnull=False),
25 Q(end_date__lt=now))
26
27
28 class Poll(models.Model):
29 """Model to represent polls"""
30 start_date = models.DateTimeField(db_index=True,
31 help_text='Date/time the poll will be eligible for voting.',)
32 end_date = models.DateTimeField(blank=True, null=True, db_index=True,
33 help_text='Date/time the poll will be ineligible for voting. '\
34 'Leave blank for an open ended poll.')
35 is_enabled = models.BooleanField(default=True, db_index=True,
36 help_text='Check to allow the poll to be viewed on the site.')
37 question = models.CharField(max_length=200)
38
39 objects = PollManager()
40
41 def __unicode__(self):
42 return self.question
43
44 class Meta:
45 ordering = ('-start_date', )
46 get_latest_by = 'start_date'
47
48 @models.permalink
49 def get_absolute_url(self):
50 return ('polls.views.poll_detail', [str(self.id)])
51
52 def results(self):
53 """
54 Returns a tuple; element 0 is the total votes, element 1 is a list of
55 {choice, votes, pct}
56 """
57 choices = []
58 total_votes = 0
59 for choice in self.choice_set.all():
60 total_votes += choice.votes
61 choices.append({'choice': choice.choice, 'votes': choice.votes, 'pct': 0.0})
62
63 if total_votes > 0:
64 for choice in choices:
65 choice['pct'] = float(choice['votes']) / total_votes * 100.0
66
67 return (total_votes, choices)
68
69 def is_open(self):
70 now = datetime.datetime.now()
71 return self.start_date <= now and (not self.end_date or now <= self.end_date)
72
73 def can_comment_on(self):
74 return self.is_open()
75
76
77 class Choice(models.Model):
78 """Model for poll choices"""
79 poll = models.ForeignKey(Poll)
80 choice = models.CharField(max_length = 200)
81 votes = models.IntegerField(default = 0)
82
83 def __unicode__(self):
84 return self.choice