Suggestions for a django db structure

Posted by rh0dium on Stack Overflow See other posts from Stack Overflow or by rh0dium
Published on 2010-04-20T21:26:12Z Indexed on 2010/04/20 21:53 UTC
Read the original article Hit count: 232

Filed under:
|
|

Hi

Say I have the unknown number of questions. For example:

  • Is the sky blue [y/n]
  • What date were your born on [date]
  • What is pi [3.14]
  • What is a large integ [100]

Now each of these questions poses a different but very type specific answer (boolean, date, float, int). Natively django can happily deal with these in a model.

class SkyModel(models.Model):
    question = models.CharField("Is the sky blue")
    answer = models.BooleanField(default=False)

class BirthModel(models.Model):
    question = models.CharField("What date were your born on")
    answer = models.DateTimeField(default=today)

class PiModel(models.Model)
    question = models.CharField("What is pi")
    answer = models.FloatField()

But this has the obvious problem in that each question has a specific model - so if we need to add a question later I have to change the database. Yuck. So now I want to get fancy - How do a set up a model where by the answer type conversion happens automagically?

ANSWER_TYPES = (
    ('boolean', 'boolean'),
    ('date', 'date'),
    ('float', 'float'),
    ('int', 'int'),
    ('char', 'char'),
)

class Questions(models.model):
    question = models.CharField(()
    answer = models.CharField()
    answer_type = models.CharField(choices = ANSWER_TYPES)
    default = models.CharField()

So in theory this would do the following:

  • When I build up my views I look at the type of answer and ensure that I only put in that value.
  • But when I want to pull that answer back out it will return the data in the format specified by the answer_type. Example 3.14 comes back out as a float not as a str.

How can I perform this sort of automagic transformation? Or can someone suggest a better way to do this?

Thanks much!!

© Stack Overflow or respective owner

Related posts about python

Related posts about django-models