用于模型形式的raw_id_fields [英] raw_id_fields for modelforms
问题描述
我有一个模型表单,其中有一个字段,该字段是模型的40,000行的ForeignKey值。默认的模型形式试图创建一个具有40,000个选项的选择框,至少可以说这不是理想的选择。
I have a modelform which has one field that is a ForeignKey value to a model which as 40,000 rows. The default modelform tries to create a select box with 40,000 options, which, to say the least is not ideal. Even more so when this modelform is used in a formset factory!
在管理员中,使用 raw_id_fields $ c可以轻松避免这种情况。 $ c>,但似乎没有等效的模型形式。我该怎么做?
In the admin, this is easiely avoidable by using "raw_id_fields
", but there doesn't seem to be a modelform equivalent. How can I do this?
这是我的模型形式:
class OpBaseForm(ModelForm):
base = forms.CharField()
class Meta:
model = OpBase
exclude = ['operation', 'routes']
extra = 0
raw_id_fields = ('base', ) #does nothing
第一行粗体字通过不创建庞大笨拙的选择框而起作用,但是当我尝试保存这种形式的字段集时,出现错误: OpBase.base必须是 Base实例。为了保存模型表单, base必须是Base实例。显然,基本主键的字符串表示形式还不够(至少不是自动)。我需要某种机制将表单中提供的字符串更改为Base实例。而且这种机制必须在表单集中起作用。有任何想法吗?如果仅 raw_id_fields
可以工作,这将很容易。但据我所知,它仅在管理员中可用。
The first bolded line works by not creating the huge unwieldy selectbox, but when I try to save a fieldset of this form, I get the error: "OpBase.base" must be a "Base" instance. In order for the modelform to be saved, 'base' needs to be a Base instance. Apparently, a string representation of a Base primary key isn't enough (at least not automatically). I need some kind of mechanism to change the string that is given my the form, to a Base instance. And this mechanism has to work in a formset. Any ideas? If only raw_id_fields
would work, this would be easy as cake. But as far as I can tell, it only is available in the admin.
推荐答案
您需要更改 widget 表示 base
字段,而不是字段类型。我认为这会起作用:
You need to change the widget for the base
field, not the field type. I think this would work:
class OpBaseForm(ModelForm):
base = forms.ModelChoiceField(queryset=Base.objects.all(),
widget=forms.TextInput)
class Meta:
model = OpBase
... etc...
这篇关于用于模型形式的raw_id_fields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!