Django 中外键模型字段的自定义表单字段

Custom form field for Foreign key model field in Django

我有模型表格:

class FooForm(forms.ModelForm):
    Meta:
        model = Bar
        fields = ('baz', 'description')

我的酒吧 class 是:

class Bar:
    baz = models.ForeignKey(Baz)
    description = models.CharField(max_length=100)

问题是 Baz class 有很多条目,并且 django's documentation says it uses ModelChoiceField 对于效率非常低的 baz 字段:

class ModelChoiceField(**kwargs)

Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for ModelChoiceField becomes impractical when the number of entries increases. You should avoid using it for more than 100 items.

问题是我找不到如何避免使用它。

换句话说,我想知道如何将 模型字段 之间的默认映射更改为 表单字段 并将另一个字段用作外键字段?

同样在我的特殊情况下,我只想在我的 ModelForm 中 show baz 字段并被禁用,所以除了 ModelChoiceField 的低效率问题之外,它也不适合这种用法。

最后我找到了满足我需求的解决方案,但我会接受任何更笼统的答案,解释什么是在需要时避免使用 ModelChoiceField 的最佳做法:)

我只需要将 FooForm 更改为:

class BuzCustomField(forms.CharField):

    def clean(self, value):
        """
        Validates the given value and returns its "cleaned" value as an
        appropriate Python object.

        Raises ValidationError for any errors.
        """
        value = self.to_python(value)
        value = Buz.objects.get(value)
        self.validate(value)
        self.run_validators(value)
        return value

class FooForm(forms.ModelForm):
    baz = forms.BuzCustomField()

    Meta:
        model = Bar
        fields = ('baz', 'description')

我再次提到我只需要显示 baz 所以使用 BuzCustomField 并不适用于所有情况。