I have a "Parent" model, which contains multiple "Child" models and the relationship between Parent and Child holds the order of the children. Thus, I need a custom intermediary model.
models.py:
class Parent(models.Model):
name = models.CharField
children = models.ManyToManyField(Child, through=ParentChild)
...
class Child(models.Model):
name = models.CharField()
...
class ParentChild(model.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
child = models.ForeignKey(Child, on_delete=models.CASCADE)
order_of_child = IntegerField(null=True, blank=True, unique=True, default=None)
A Parent object is created based on a form and the Child objects to be part of the Parent object are selected by checkboxes. Now my questions are: How can the order_of_child be included in the form and rendered alongside the checkboxes and how can the relationship be correctly saved in the view?
forms.py:
class ParentForm(ModelForm):
class Meta:
model = Parent
fields = ['name', 'children']
def __init__(self, *args, **kwargs):
super(ParentForm, self).__init__(*args, **kwargs)
self.fields['name'] = forms.CharField(label='Name', widget=forms.TextInput()
self.fields['children'] = ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(queryset=Child.objects.all())