Django:如何在使用自定义中间选项卡时将“选项”限制为

2024-06-01 06:58:00 发布

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

首先我要说的是,我使用的是一个遗留数据库,因此避免自定义中间表不是一个选择。在

我正在寻找另一种方法来获得limit_choices_to功能,因为我只需要在我的ModelForm中显示由Sampletype模型中的sample_option布尔标记的选项:

class PlanetForm(ModelForm):
    class Meta:
        model = Planet
        fields = ['name', 'samples']

这是我的模型的简化视图

^{pr2}$

Sample是中间表。 通常,如果项目是从Django开始的,我可以将ManyToManyField声明定义为:

samples = models.ManyToManyField('Sampletype', limit_choices_to={'sample_option'=True})

但这不是一个选择。。那么如何获得这个功能呢? Django在其文件中明确指出:

limit_choices_to has no effect when used on a ManyToManyField with a custom intermediate table specified using the through parameter.

但是它们没有提供关于在您有一个定制的中间表时如何实现该限制的信息。在

我尝试在Sample模型中对ForeignKey设置limit_choices_to选项,如下所示:

sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING, limit_choices_to={'sample_option': True})

但那没有效果。在

奇怪的是,我在网上找不到答案,而且很明显其他人必须在他们的项目中这样做,所以我猜这个解决方案很简单,但我无法解决。在

提前感谢您的任何帮助或建议。在


Tags: tosample模型功能models选项classchoices
1条回答
网友
1楼 · 发布于 2024-06-01 06:58:00

您可以在表单的__init__方法中设置选项:

class PlanetForm(ModelForm):

    class Meta:
        model = Planet
        fields = ['name', 'samples']

    def __init__(self, *args, **kwargs):
         super(PlanetForm, self).__init__(*args, **kwargs)

         sample_choices = list(
             Sampletype.objects.filter(sample_option=True).values_list('id', 'name')
         )
         # set these choices on the 'samples' field.
         self.fields['samples'].choices = sample_choices

相关问题 更多 >