【发布时间】:2021-07-16 22:32:13
【问题描述】:
我想在 ModelForm 中使用一个简单的外键关系,但没有 ModelChoiceField。
class Sample(models.Model):
alt = IntegerField(db_index=True, unique=True)
class Assignment(models.Model):
sample = models.ForeignKey(Sample, on_delete=models.CASCADE)
我想让 AssignmentForm 根据样本 alt 字段的内容选择样本。使用 ModelChoiceField 会是这样的:
class SampleSelect(ModelChoiceField):
def label_from_instance(self, obj):
return obj.alt
class AssignmentForm(ModelForm):
sample = SampleSelect(queryset=Sample.objects.all())
class Meta:
model = Assignment
fields = ['sample']
ModelChoiceField documentation 表示如果选择的数量很大,请使用其他东西。
允许选择单个模型对象,适合表示外键。请注意,当条目数量增加时,ModelChoiceField 的默认小部件变得不切实际。您应该避免将其用于超过 100 个项目。
我想我需要一个自定义表单域,但我不知道该怎么做。
class SampleBAltField(IntegerField):
def clean(self, value):
try:
return Sample.objects.get(alt=value)
except Sample.DoesNotExist:
raise ValidationError(f'Sample with alt {value} does not exist')
这个现有代码应该从表单中获取一个整数并将其映射回外键,但我无法弄清楚要覆盖什么来填充来自 Sample 实例的绑定表单的字段。
有没有一种相对简单的方法可以用 ModelForm 中的 FormFields 来解决这个问题,还是我需要从头开始编写 Form?
【问题讨论】:
-
看到这个grid of packages,选择适合你的。 django-autocomplete-light 是一个非常受欢迎的选项。
-
我不完全确定这个问题在这里是否非常清楚。您希望用户选择或呈现什么?您是否只想让用户输入他们知道的整数而不是从下拉列表中选择?
-
@sytech 是的,我希望用户输入一个整数,由于不值得描述的原因,他们会很熟悉。
标签: python django django-forms