我目前在我的类型数据库中有一系列对象的设置CellType
。
我似乎需要的是inline formset,它显然简化了模型之间外键关系的处理。
我想要的是一个表单集,它为每个 CellCount 实例组成一个表单,链接到数据库中的每个 CellType 对象。
cellcount_formset = inlineformset_factory(CellType,
CellCount,
form=CellCountForm,
can_delete=False)
似乎把我带向了正确的方向,但我真正想要的是用正确的 CellType 对象填充 CellCountForm 的单元格字段,从而使整个事情能够整齐地打包和保存。事实证明这比我想象的要复杂一点!
模型.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)
表格.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