首先,我要说,我正在处理遗留数据库,因此避免使用自定义中间表并不是一种选择。
我正在寻找一种获得limit_choices_to
功能的替代方法,因为我只需要在sample_option
模型中的ModelForm中显示由Sampletype
布尔值标记的选项:
class PlanetForm(ModelForm):
class Meta:
model = Planet
fields = ['name', 'samples']
下面是我的模型的简化视图
class Planet(models.Model):
name= models.CharField(unique=True, max_length=256)
samples = models.ManyToManyField('Sampletype', through='Sample')
class Sample(models.Model):
planet = models.ForeignKey(Planet, models.DO_NOTHING)
sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING)
class Sampletype(models.Model):
name = models.CharField(unique=True, max_length=256)
sample_option = models.BooleanField(default=True)
Sample
是中间表。通常,如果项目最初是用Django启动的,我只需将ManyToManyField声明定义为:
samples = models.ManyToManyField('Sampletype', limit_choices_to={'sample_option'=True})
但这不是一种选择。那么我如何获得这个功能呢?Django在文件中明确指出:
limit_choices_to在使用使用直通参数指定的自定义中间表的ManyToManyField上时没有任何效果。
但是,当您有一个自定义的中间表时,它们没有提供关于如何使这个限制就位的信息。
我尝试在limit_choices_to
模型中的ForeignKey
上设置Sample
选项,如下所示:
sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING, limit_choices_to={'sample_option': True})
但那没有效果。
奇怪的是,我在网上找不到答案,而且很明显,其他人必须在他们的项目中这样做,所以我猜解决方案真的很简单,但我想不出答案。
提前感谢您的帮助或建议。
发布于 2017-03-31 10:49:17
您可以在表单的__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
https://stackoverflow.com/questions/43121367
复制相似问题