创建新的Child
时,我只需要显示所有Parent
实例的列表,而无需父实例,因此用户可以在要添加到的实例前面设置复选框这个父母
怎么处理呢?
我需要让人们为Django表单集中的多个Child实例分配外键。我不知道该怎么做:
models.py
:
class Parent(models.Model):
pass
class Child(models.Model):
owner = models.ForeignKey(to=Parent, null=True)
forms.py
:
class PartFormset(forms.BaseInlineFormSet):
model = Child
def get_queryset(self):
return self.model.objects.filter(owner__isnull=True)
MyFormSet = inlineformset_factory(parent_model=Parent,
model=Child,
formset=PartFormset,
extra=0,
can_delete=False,
)
这个显然不起作用,因为inlineformset_factory
遗漏了fields
参数。但是,如果我提供“所有者”作为字段,那当然也不起作用。
答案 0 :(得分:1)
class PartFormset(forms.BaseInlineFormSet):
model = Child
def get_queryset(self):
return self.model.objects.filter(owner__isnull=True)
# it works as your mind with jumping over the related method of BaseInlineFormSet,
# but you need notice the validate and clean stuff
def add_fields(self, form, index):
super(forms.BaseInlineFormSet, self).add_fields(form, index)