pollmodel.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from datetime import timedelta
  2. from django.db import models
  3. from django.utils import timezone
  4. import base64
  5. try:
  6. import cPickle as pickle
  7. except ImportError:
  8. import pickle
  9. class Poll(models.Model):
  10. forum = models.ForeignKey('Forum')
  11. thread = models.OneToOneField('Thread', primary_key=True)
  12. user = models.ForeignKey('User', null=True, blank=True, on_delete=models.SET_NULL)
  13. start_date = models.DateTimeField()
  14. length = models.PositiveIntegerField(default=0)
  15. question = models.CharField(max_length=255)
  16. max_choices = models.PositiveIntegerField(default=0)
  17. _choices_cache = models.TextField(db_column='choices_cache')
  18. votes = models.PositiveIntegerField(default=0)
  19. vote_changing = models.BooleanField(default=False)
  20. public = models.BooleanField(default=False)
  21. class Meta:
  22. app_label = 'misago'
  23. @property
  24. def end_date(self):
  25. return self.start_date + timedelta(days=self.length)
  26. @property
  27. def over(self):
  28. if not self.length:
  29. return False
  30. return timezone.now() > self.end_date
  31. @property
  32. def choices_cache(self):
  33. if self._cache:
  34. return self._cache
  35. try:
  36. self._cache = pickle.loads(base64.decodestring(self._choices_cache))
  37. except Exception:
  38. self._cache = {}
  39. return self._cache
  40. @choices_cache.setter
  41. def choices_cache(self, choices):
  42. choices_cache = {'order': [], 'choices': {}}
  43. for choice in choices:
  44. choices_cache['order'].append(choice.pk)
  45. choices_cache['choices'][choice.pk] = choice
  46. self._cache = choices_cache
  47. self._choices_cache = base64.encodestring(pickle.dumps(choices_cache, pickle.HIGHEST_PROTOCOL))