我不确定。但在我的项目中,我这样做了。填写表格的计数 = 计数(未删除现有)+ 计数(已更改且未删除新的)。在干净的方法中,我们确定所有表格都已经过验证(并且不包含空白表格)。
表格.py:
class AnswersFormsetBase(forms.models.BaseInlineFormSet):
def clean(self):
super(AnswersFormsetBase, self).clean()
initial_num = len(filter(lambda f: not self._should_delete_form(f), self.initial_forms))
extra_num = len(filter(lambda f: f.has_changed() and not self._should_delete_form(f), self.extra_forms))
if initial_num + extra_num < 2:
raise ValidationError("Polling should be at least two possible answers")
AnswerFormset = inlineformset_factory(Polling, Answer, formset=AnswersFormsetBase)
管理员.py:
class AnswersInline(admin.TabularInline):
model = Answer
fk_name = "polling"
formset = AnswerFormset # from forms.py
class PollingModelAdmin(admin.ModelAdmin):
inlines = [AnswersInline]
admin.site.register(Polling, PollingModelAdmin)