假设我有一些人为的模型:
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”对象没有“作者”属性。所以,我也尝试过这样的事情,我尝试覆盖 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
产生相同的结果。
有人知道这是怎么做的吗?