should be able to accomplish a variety of things, from actual helpful facts to quotes to fortune commands
64 lines
1.3 KiB
Python
64 lines
1.3 KiB
Python
"""Store "facts"."""
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
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)
|
|
|
|
class Meta:
|
|
verbose_name_plural = 'fact categories'
|
|
|
|
def __unicode__(self):
|
|
"""String representation."""
|
|
|
|
return "{0:s}".format(self.name)
|
|
|
|
|
|
class FactManager(models.Manager):
|
|
|
|
"""Queries against Fact."""
|
|
|
|
def random_fact(self, category, regex=None):
|
|
"""Get a random fact from the database."""
|
|
|
|
try:
|
|
fact_category = FactCategory.objects.get(name=category)
|
|
except FactCategory.DoesNotExist:
|
|
return None
|
|
|
|
facts = Fact.objects.filter(category=fact_category)
|
|
if regex:
|
|
facts = facts.filter(fact__iregex=regex)
|
|
|
|
if len(facts) > 0:
|
|
return random.choice(facts)
|
|
else:
|
|
return None
|
|
|
|
|
|
class Fact(models.Model):
|
|
|
|
"""Define facts."""
|
|
|
|
fact = models.TextField()
|
|
category = models.ForeignKey(FactCategory)
|
|
|
|
objects = FactManager()
|
|
|
|
def __unicode__(self):
|
|
"""String representation."""
|
|
|
|
return "{0:s} - {1:s}".format(self.category.name, self.fact)
|