2012-08-01 117 views
0

我想有一組與個人答案的問題,每個用戶都可以回答。 爲了實現這種功能,我建立了以下型號:Django模型和管理內聯

models.py:

class Question(models.Model): 
    question = models.TextField(null=False) 

class PossibleAnswer(models.Model): 
    question=models.ForeignKey(Question, related_name="possible_answer") 
    answer = models.CharField(max_length=200) 

class Answer(models.Model): 
    question = models.ForeignKey(Question) 
    user = models.ForeignKey(User) 
    real_answer = models.ForeignKey(PossibleAnswer, related_name="real_answer") 

最初管理界面就足夠了,這些問題的工作。它應該是可見的「每個問題」的基礎上,因而有「問題」應該顯示它允許答案和答案的用戶可以給:

admin.py:

class AnswerInline(admin.TabularInline): 
    model = Answer 

class PossibleAnswerInline(admin.TabularInline): 
    model = PossibleAnswer 

class QuestionAdmin(admin.ModelAdmin): 
    inlines = [PossibleAnswerInline, AnswerInline] 

admin.site.register(Question, QuestionAdmin) 

一切都很正常,直到我保存了產生IntegrityError的答案。我相信這涉及到對象之間的依賴關係?

第二項我不能讓周圍的:以限制real_answer實際選項的選擇(即都涉及到這個問題),我定義的forms.py如下:

class AnswerForm(ModelForm): 
    class Meta: 
    model = Answer 

    def __init__(self, *args, **kwargs): 
    super(AnswerForm, self).__init__(*args, **kwargs) 
    choices = self.instance.question.possible_answer.all() 
    self.fields["real_answer"].choices = choices 

,並用它admin.py如下:

class AnswerInline(admin.TabularInline): 
    model = Answer 
    form = AnswerForm 

當我運行此,self.instance.question.possible_answer.all()總是提高DoesNotExist

任何指針都非常感謝。

最佳,

安德烈亞斯

回答

0

AnswerForm被初始化,它的實例屬性不會總是有與此相關的一個問題對象,所以任何時候你從表單中引用self.instance.question,將DoesNotExist異常將是如果還沒有附加到表單答案對象的問題實例,則拋出它。

在窗體的init試試這個代碼,而不是方法:

choices = [] 
if self.instance.pk 
    questions = Question.objects.filter(answer=self.instance) 
    if questions.exist(): 
     choices = questions.get().possibleanswer_set.all() 
+0

偉大的方式,它幾乎工作。 當django admin顯示錶單時,是否有限制選項的方法呢?在已有的答案中,它可以工作,但不在底部的新行中。 – 2012-08-01 19:35:39

+0

應該有,是的,請參考Django的管理員(和可能的形式)的文檔。 – 2012-08-01 19:45:05

+0

不應該在AnswerForm中嗎? – 2012-08-01 20:14:36

0

我主要建立在@ GonzaloDelgado的答案,但我不覺得他的代碼是最優的。最好使用try...except塊。

from django.core.exceptions import ObjectDoesNotExist 
... 
def __init__(self, *args, **kwargs): 
    super(AnswerForm, self).__init__(*args, **kwargs) 

    if self.instance.pk: 
     try: 
      self.fields['real_answer'].queryset = self.question.possibleanswer_set.all() 
     except ObjectDoesNotExist: 
      pass 
+0

你總是可以編輯我的答案:-) – 2012-08-01 20:17:12

+0

不適合這樣的事情。編輯會(並且應該)被拒絕,因爲它是一個「根本性的改變:這個編輯在原來的文章中變化太大了,原本的意義或意圖將會丟失。」 – 2012-08-01 20:24:28

+0

對不起,我不會想到重構我的代碼(使其成爲「最優」)會失去我的答案的含義或意圖。 – 2012-08-01 20:34:57