6

假设我有一些人为的模型:

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

产生相同的结果。

有人知道这是怎么做的吗?

4

2 回答 2

9

尽管卡尔对这些领域的看法是正确的,但您也错过了一个超级类的电话。我就是这样做的:

class BookForm(ModelForm):
    author = ModelMultipleChoiceField(queryset=Author.objects.all())

    class Meta:
        model = Book

    def __init__(self, *args, **kwargs):
        letter = kwargs.pop('letter')
        super(BookForm, self).__init__(*args, **kwargs)
        choices = getChoices(letter)
        self.fields['author'].queryset = choices
于 2009-04-10T18:36:19.747 回答
8

表单对象没有字段作为属性,您需要查看“字段”属性,这是一个字典:

self.fields['author'].queryset = choices

如果您想完全了解这里发生了什么,您可能会对这个答案感兴趣- 它是关于模型的,但表单的工作方式类似。

于 2009-04-10T18:30:45.530 回答