在Django中为外键模型字段创建自定义表单字段

2024-04-25 11:40:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型表格:

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

我的酒吧课程是:

^{pr2}$

问题是Baz类有很多条目,而作为django's documentation says它使用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中显示baz字段并将其禁用,因此除了ModelChoiceField的低效问题外,它也不适合这种用法。在


Tags: ofthe模型formodelbarformsbaz
1条回答
网友
1楼 · 发布于 2024-04-25 11:40:51

最后,我找到了一个满足我需求的解决方案,但我会接受任何更一般的答案,解释在需要时避免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并不适合所有情况。在

相关问题 更多 >

    热门问题