动态Django模型控制

时间:2012-01-29 03:22:48

标签: django

我正在使用django设计一个测验引擎。 在models.py中,我有这样的类:

class Quiz (models.Model):
    quiz_id = models.AutoField (primary_key=True)
    problem_desc = models.TextField (blank=True)
    problem_has_resource = models.BoolField ()
    problem_is_choice = models.BooleanField ()
    def __unicode__ (self):
        return self.quiz_id

class Choice (models.Model):
    choice_id = models.AutoField (primary_key=True)
    quiz_id = models.ForeignKey (Quiz);
    choice_desc = models.CharField (max_length = 500)
    is_answer = models.BooleanField ()

class Answer (models.Model):
    quiz_id = models.ForeignKey (Quiz)
    input_answer = models.FloatField ()

class Quiz_Resource (models.Model):
    quiz_id = models.ForeignKey (Quiz)
    title = form.CharField (max_length = 50)
    file = forms.FileField ()
    def __unicode__ (self):
        return self.file.name

测验可能需要输入“答案”或选择一个选项。测验可能有很多选择。测验可能有一些额外的资源。我希望boolfield控制管理页面样式,设置正式信息。我怎样才能实现它?

低头,谢谢!

在这里输入代码

1 个答案:

答案 0 :(得分:1)

首先,您必须将测验模型与您的Choice,Answer和Quiz_Ressource模型联系起来。

class Quiz (models.Model):
    name = models.TextField(max_length=50)
    problem_desc = models.TextField (blank=True)
    problem_has_resource = models.BoolField ()
    problem_is_choice = models.BooleanField ()

    choices=models.ManyToManyField(Choice)
    answers=models.ManyToManyField(Answer)
    ressources=models.ManyToManyField(Quiz_Ressource)

这样你告诉Django你的Quiz模型引用了Choice,Answer和Quiz_Ressource类型的多个模型。如果不清楚,可以在关系数据库中搜索ManyToMany的概念。

在您重写了这样的模型之后,会有一些字段用于在管理页面上添加和选择选项,答案和资源。

要继续使用django,请使用此处提供的文档:https://docs.djangoproject.com/en/1.3/topics/db/models/#many-to-many-relationships

您对自定义管理模板的需求是另一回事。您可以在应用程序admin.py中执行此类操作:

from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from yourapp.models import Quiz

class QuizAdminSite(AdminSite):

    def admin_quiz(request):
        #here goes your custom admin view code, where you can do
        #if has_ressource: return render_to_response('admin/quiz/has_ressource.html')
        #elif is_choice: return render_to_response('admin/quiz/is_choice.html')
        #and so on, you have to work out yourself how this has to look exactly
        return HttpResponse('your custom admin view')

    def get_urls(self):
    from django.conf.urls.defaults import *
    urls = super(ItemAdmin, self).get_urls()
    my_urls = patterns('',
        url(
            r'update_feeds',
            self.admin_site.admin_view(self.admin_quiz),
            name='admin_quiz',
        ),
    )
    return my_urls + urls    


class QuizAdmin(QuizAdminSite):
    model=Quiz

admin.site.register(Quiz,QuizAdmin)

我不知道你想要用自定义管理员视图做什么,所以我跳过那部分。但这应该是要遵循的道路。