2013-10-21 105 views
1

我已經在Django以下車型(簡化了可讀性):編輯多個嵌套模型

class Test(models.Model): 
    pass 

class Page(models.Model): 
    test = models.ForeignKey(Test) 

class Question(models.Model); 
    page = models.ForeignKey(Page) 

class Answer(models.Model): 
    question = models.ForeignKey(Question) 

我想充分編輯在管理方面的測試,這是編輯Test數據,爲該測試添加Page s,然後依次爲每個問題添加Question s和Answer s。 什麼是最簡單的和Django-ish模式呢?

回答

1
from django.contrib import admin 
from project.apps.models import Test, Page,Question, Answer 

class AnswerInline(admin.StackedInline): 
model = Answer 
extra = 0 

class QuestionInline(admin.StackedInline): 
model = Question 
extra = 0 

class PageInline(admin.StackedInline): 
model = Page 
extra = 0 

class TestAdmin(admin.ModelAdmin): 
list_display =('__unicode__','item1','item2') 
search_fields = ('field1','field2') 
inlines=[AnswersItemInline,QuestionsItemInline,PageItemInline] 

admin.site.register(Test,TestAdmin) 
+0

在你的例子中,我需要外鍵才能將'Question's和'Answer'作爲內聯包含到'Test'中。 – linkyndy

+0

TestAdmin中的inlines = []會執行此操作。如果我明白你想要什麼,你可以忽略search_fields – 2013-10-21 13:30:25

+0

不,我的意思是我不能在'TestAdmin'' inlines = []'中包含'QuestionInline'和'AnswerInline',因爲應該鏈接這些模型的外鍵缺失。這是發生的異常:'沒有ForeignKey到' – linkyndy