【发布时间】:2012-10-02 03:28:55
【问题描述】:
我目前在我的数据库中设置了一系列 CellType 类型的对象。
我似乎需要的是inline formset,它显然简化了模型之间外键关系的处理。
我想要的是一个表单集,它为每个 CellCount 实例组成一个表单,链接到数据库中的每个 CellType 对象。
cellcount_formset = inlineformset_factory(CellType,
CellCount,
form=CellCountForm,
can_delete=False)
似乎把我带向了正确的方向,但我真正想要的是用正确的 CellType 对象填充 CellCountForm 的单元格字段,从而让整个事情被整齐地打包和保存。事实证明这比我想象的要复杂一点!
models.py
class CellType(models.Model):
readable_name = models.CharField(max_length=50)
machine_name = models.CharField(max_length=50)
comment = models.TextField(blank=True)
class CellCount(models.Model):
cell_count_instance = models.ForeignKey(CellCountInstance)
cell = models.ForeignKey(CellType)
normal_count = models.IntegerField()
abnormal_count = models.IntegerField()
comment = models.TextField(blank=True)
forms.py
class CellCountForm(ModelForm):
auto_id = False
class Meta:
model = CellCount
widgets = {
'cell': HiddenInput(),
'normal_count': HiddenInput,
'abnormal_count': HiddenInput}
exclude = ('cell_count_instance', 'comment',)
这些小部件是隐藏的,因为它们是由后台基于 JQuery 的计算器填充的。
理想情况下,我要使用的伪代码逻辑是:
formset containing:
(x) CellCount forms,
the cell field of which is populated with the CellType object
(x) = number of CellTypes in the database
【问题讨论】:
标签: django django-views django-forms inline-formset