gremmie@1: ''' gremmie@1: Models for the Polls application. gremmie@1: ''' gremmie@1: gremmie@1: import datetime gremmie@1: from django.db import models gremmie@1: from django.db.models import Q gremmie@1: gremmie@1: gremmie@1: class PollManager(models.Manager): gremmie@1: """Manager for the Poll model""" gremmie@1: gremmie@1: def get_current_polls(self): gremmie@1: now = datetime.datetime.now() gremmie@1: return self.filter( gremmie@1: Q(is_enabled=True), gremmie@1: Q(start_date__lte=now), gremmie@1: Q(end_date__isnull=True) | Q(end_date__gte=now)) gremmie@1: gremmie@1: def get_old_polls(self): gremmie@1: now = datetime.datetime.now() gremmie@1: return self.filter( gremmie@1: Q(is_enabled=True), gremmie@1: Q(end_date__isnull=False), gremmie@1: Q(end_date__lt=now)) gremmie@1: gremmie@1: gremmie@1: class Poll(models.Model): gremmie@1: """Model to represent polls""" gremmie@1: start_date = models.DateTimeField(db_index=True, gremmie@1: help_text='Date/time the poll will be eligible for voting.',) gremmie@1: end_date = models.DateTimeField(blank=True, null=True, db_index=True, gremmie@1: help_text='Date/time the poll will be ineligible for voting. '\ gremmie@1: 'Leave blank for an open ended poll.') gremmie@1: is_enabled = models.BooleanField(default=True, db_index=True, gremmie@1: help_text='Check to allow the poll to be viewed on the site.') gremmie@1: question = models.CharField(max_length=200) gremmie@1: gremmie@1: objects = PollManager() gremmie@1: gremmie@1: def __unicode__(self): gremmie@1: return self.question gremmie@1: gremmie@1: class Meta: gremmie@1: ordering = ('-start_date', ) gremmie@1: get_latest_by = 'start_date' gremmie@1: gremmie@1: @models.permalink gremmie@1: def get_absolute_url(self): gremmie@1: return ('polls.views.poll_detail', [str(self.id)]) gremmie@1: gremmie@1: def results(self): gremmie@1: """ gremmie@1: Returns a tuple; element 0 is the total votes, element 1 is a list of gremmie@1: {choice, votes, pct} gremmie@1: """ gremmie@1: choices = [] gremmie@1: total_votes = 0 gremmie@1: for choice in self.choice_set.all(): gremmie@1: total_votes += choice.votes gremmie@1: choices.append({'choice': choice.choice, 'votes': choice.votes, 'pct': 0.0}) gremmie@1: gremmie@1: if total_votes > 0: gremmie@1: for choice in choices: gremmie@1: choice['pct'] = float(choice['votes']) / total_votes * 100.0 gremmie@1: gremmie@1: return (total_votes, choices) gremmie@1: gremmie@1: def is_open(self): gremmie@1: now = datetime.datetime.now() gremmie@1: return self.start_date <= now and (not self.end_date or now <= self.end_date) gremmie@1: gremmie@1: def can_comment_on(self): gremmie@1: return self.is_open() gremmie@1: gremmie@1: gremmie@1: class Choice(models.Model): gremmie@1: """Model for poll choices""" gremmie@1: poll = models.ForeignKey(Poll) gremmie@1: choice = models.CharField(max_length = 200) gremmie@1: votes = models.IntegerField(default = 0) gremmie@1: gremmie@1: def __unicode__(self): gremmie@1: return self.choice