私がいくつかの考案されたモデルを持っているとしましょう:
class Author(Model):
name = CharField()
class Book(Model):
title = CharField()
author = ForeignKey(Author)
そして、Bookに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'オブジェクトには属性'author'がありません。そこで、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
同じ結果が得られます。
これがどのように行われるのか知っている人はいますか?