Django inline formset multiple models

2019-08-25 23:32发布

TL;DR: I need a some kind of formset for formsets.

I have two different models related to one buisness-entity, and I need to make a form to edit both models like a one form. And I need to create a lot of such forms on the one page like djngo inline formset does.

Now I have the following thing:

class Parent(models.Model):
  name = models.Charfield()

class FirstChild(models.Model):
  name = models.Charfield()
  e_id = models.IntegerField()
  parent = models.ForeignKey(Parent)

class FirstChildForm(django.forms.ModelForm):
    class Meta:
        model = Child
        fields = ('name', 'e_id', 'parent')
        widgets = {'parent': forms.TextInput}

And I render a lot of them usiing inline formsets:

formset_class = inlineformset_factory(Parent, FirstChild, 
                                      form=FirstChildForm, extra=1)

But now I have to add second child model and a form for it, and still render it like an one inline form, bit make it form actually edit two models. Like this:

class SecondChild(models.Model):
  name = models.Charfield()
  e_id = models.IntegerField()
  parent = models.ForeignKey(Parent)

class SecondChildForm(django.forms.ModelForm):
    class Meta:
        model = Child
        fields = ('name', 'e_id', 'parent')
        widgets = {'parent': forms.TextInput}

formset_class = inlineformset_factory(models=[Parent, FirstChild], 
                                      forms=[FirstChildForm, SecondChildForm], 
                                      extra=1)

As far as I understand, Django formsets cannot work with multiple models right now.

So which way should I choose to implement this behaviour and do not broke all django conceptions? I cannot use some extra libraries so I have to implement everything by myself and I use django 1.6 if it is important.

标签: django forms
1条回答
霸刀☆藐视天下
2楼-- · 2019-08-26 00:20
登录 后发表回答