dr.botzo/facts/models.py

64 lines
1.6 KiB
Python

"""Store "facts"."""
import logging
import random
from django.db import models
log = logging.getLogger('facts.models')
class FactCategory(models.Model):
"""Define categories for facts."""
name = models.CharField(max_length=200, unique=True)
show_all_entries = models.BooleanField(default=False)
show_source = models.BooleanField(default=False)
class Meta:
"""Meta options."""
verbose_name_plural = 'fact categories'
def __str__(self):
"""String representation."""
return "{0:s}".format(self.name)
def random_fact(self, regex=None):
"""Get a random fact in this category."""
facts = self.fact_set.all()
if regex:
facts = facts.filter(fact__iregex=regex)
if len(facts) > 0:
return random.choice(facts)
else:
return None
class FactManager(models.Manager):
"""Queries against Fact."""
def random_fact(self, category, regex=None):
"""Get a random fact from the database."""
try:
factcategory = FactCategory.objects.get(name=category)
except FactCategory.DoesNotExist:
return None
return factcategory.random_fact(regex)
class Fact(models.Model):
"""Define facts."""
fact = models.TextField()
category = models.ForeignKey(FactCategory)
nickmask = models.CharField(max_length=200, default='', blank=True)
time = models.DateTimeField(auto_now_add=True)
objects = FactManager()
def __str__(self):
"""String representation."""
return "{0:s} - {1:s}".format(self.category.name, self.fact)