的選擇比方說,我有一些做作型號:如何修改ModelMultipleChoiceField
class Author(Model):
name = CharField()
class Book(Model):
title = CharField()
author = ForeignKey(Author)
而且我們說,我想使用的ModelForm的書:
class BookForm(ModelForm):
class Meta:
model = Book
簡單爲止。但是讓我們也說我的數據庫中有很多作者,而且我不想有這麼長的多選題。所以,我想要限制BookForm的ModelMultipleChoiceField作者字段上的查詢集。我們還要說,我想要的查詢集只能在__init__
之前選擇,因爲它依賴於要傳遞的參數。
這似乎是它可能做的伎倆:
class BookForm(ModelForm):
class Meta:
model = Book
def __init__(self, letter):
# returns the queryset based on the letter
choices = getChoices(letter)
self.author.queryset = choices
當然,如果這只是工作,我就不會在這裏。這讓我一個AttributeError。 'BookForm'對象沒有屬性'作者'。所以,我也嘗試過這樣的事情,在這裏我試圖重寫的ModelForm的默認域,然後將其設:
class BookForm(ModelForm):
author = ModelMultipleChoiceField(queryset=Author.objects.all())
class Meta:
model = Book
def __init__(self, letter):
choices = getChoices(letter)
self.author.queryset = choices
將會產生相同的結果。
任何人都知道這是如何完成的?
是的,我真正的問題領域有超類調用,但我跳過了這個例子。 – Brian 2009-04-10 18:38:05