用于子类的Django模型/数据库设计

时间:2010-06-23 16:45:27

标签: python django database-design django-models django-admin

好的,我很难描述。这是一个关系诊断。 relationship diag http://img248.imageshack.us/img248/3568/surveyrel.jpg

在Django中我的模型如下:

from django.db import models
from datetime import datetime

class Survey(models.Model):
    name = models.CharField(max_length=100)
    pub_date = models.DateTimeField('date published',default=datetime.now)
    def __unicode__(self):
        return self.name

# This model should be abstracted by a more specific model
class Section(models.Model):
    survey = models.ForeignKey(Survey)
    name = models.CharField(max_length=100)
    def __unicode__(self):
        return self.name

# Models for supporting the 'ratings' mode
class RatingSection(Section):
    pass

class RatingQuestion(models.Model):
    section = models.ForeignKey(RatingSection)
    name = models.CharField(max_length=255)
    def __unicode__(self):
        return self.name

class RatingAnswer(models.Model):
    section = models.ForeignKey(RatingSection)
    name = models.CharField(max_length=60)
    def __unicode__(self):
        return self.name

class RatingVotes(models.Model):
    question = models.ForeignKey(RatingQuestion)
    answer = models.ForeignKey(RatingAnswer)
    votes = models.PositiveIntegerField(default=0)
    def __unicode__(self):
        return self.votes + self.answer.name + ' votes for ' + self.question.name

# Models for supporting the 'multichoice' mode
class MultiChoiceSection(Section):
    can_select_multiple = models.BooleanField()

class MultiChoiceQuestion(models.Model):
    section = models.ForeignKey(MultiChoiceSection)
    name = models.CharField(max_length=255)
    def __unicode__(self):
        return self.name

class MultiChoiceAnswer(models.Model):
    section = models.ForeignKey(MultiChoiceSection)
    name = models.CharField(max_length=60)
    votes = models.PositiveIntegerField(default=0)
    def __unicode__(self):
        return self.name

问题在于我几乎可以肯定这不是正确的方法,即使它是,我也无法弄清楚如何让Django中的管理区域向用户显示一个选择,询问是什么他们想要的部分子类型。

构建此类模型的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您也可以拥有一个分部类,其属性type可以是评级或多选 - 这将在管理员中呈现,然后作为选择框呈现。
但我认为你应该看看Django创建抽象模型的可能性:http://docs.djangoproject.com/en/dev/topics/db/models/#id6

class Section(models.Model):
    survey = models.ForeignKey(Survey)
    name = models.CharField(max_length=100)

    class Meta:
        abstract = True        # no db table created for this model

    def __unicode__(self):
        return self.name


class RatingSection(Section):
    pass

class MultiChoiceSection(Section):
    can_select_multiple = models.BooleanField()