如何阻止Django ModelForm为外键创建选择 [英] How to Stop Django ModelForm From Creating Choices for a Foreign Key

查看:82
本文介绍了如何阻止Django ModelForm为外键创建选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django模型,其中的外键指向包含约50,000条记录的表。我正在使用Django Forms.ModelForm创建表单。问题是我只需要外键指向的表中一小部分记录。

I have a Django model with a Foreign key to a table that contains about 50,000 records. I am using the Django forms.ModelForm to create a form. The problem is I only need a small subset of the records from the table the Foreign key points to.

我能够在初始化方法。如何防止ModelForm创建该初始选择集?

I am able to create that subset of choices in the init method. How can I prevent ModelForm from creating that initial set of choices?

我尝试在Meta方法中使用widgets参数。但是Django调试工具栏指示数据库仍在命中。

I tried using the widgets parameter in the Meta method. But Django debug toolbar indicates the database is still being hit.

谢谢

推荐答案

自动生成的 ModelChoiceField 会将其 queryset 初始化为默认值。小部件不是您应该自定义 queryset 属性的位置。

The autogenerated ModelChoiceField will have its queryset initialized to the default. The widget is not where you are supposed to customize the queryset property.

定义手动选择ModelChoiceField ,将其 queryset 初始化为空。请记住将 ModelChoiceField 命名为与自动生成的名称相同,并记得在 fields 元组。现在,您可以从构造函数中设置 queryset ,避免数据库被击中两次。

Define the ModelChoiceField manually, initialize its queryset to be empty. Remember to name the ModelChoiceField the same as the one that would have been automatically generated, and remember to mention that field in the fields tuple. Now you can set the queryset from the constructor and avoid the database being hit twice.

如果您很幸运(并且您可能会进行测试),在构造过程中未对 queryset 进行评估,在这种情况下,请定义 ModelChoiceField

If you are lucky (and you probably are, please test though), the queryset has not been evaluated during construction, and in that case, defining the ModelChoiceField manually is not required.

class YourModelForm(ModelForm):
    your_fk_field_name = forms.ModelChoiceField(queryset=YourModel.objects.none())

    class Meta:
        model = YourModel
        fields = ('your_fk_field_name', .......)

    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['your_fk_field_name'].queryset = ....

这篇关于如何阻止Django ModelForm为外键创建选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆