Python Django-使用其他模型的外键保存ModelForm

Python Django-使用其他模型的外键保存ModelForm,python,django,django-forms,Python,Django,Django Forms,我正在用这些模型创建一个民意测验应用程序 class Poll(BaseModel): title = models.CharField(max_length=255) end_date = models.DateField() class Choice(BaseModel): poll = models.ForeignKey('Poll') choice = models.CharField(max_length=255) index = models.IntegerFi

我正在用这些模型创建一个民意测验应用程序

class Poll(BaseModel):
  title = models.CharField(max_length=255)
  end_date = models.DateField()

class Choice(BaseModel):
  poll = models.ForeignKey('Poll')
  choice = models.CharField(max_length=255)
  index = models.IntegerField()
一次投票可以有很多选择——每次投票的数量都会有所不同。我正在努力弄清楚如何通过modelform保存投票,同时保存相关的选择

我知道我必须重写PollForm中的Save和Clean方法,但是在那之后,它有点复杂。我知道有一种更像python/djangosque的方法。我最困惑的是选择和投票之间的关系,因为它只在一个方向上定义

此外,当使用一组选项更新民意测验时,我不知道这将如何工作,其中有些选项存在,有些是新的。当然,下面的代码不起作用,但我正是这么想的。我希望你能朝着正确的方向轻推我

class PollForm:
  def save(self, choices, commit=True, *args, **kwargs):

    poll = super(PollForm, self).save(commit=False, *args, **kwargs)

    if commit:

      p = poll.save()

      for choice in choices:
        choice['poll_id'] = p.id

        if choice['id']:
          c = ChoiceForm(choice, instance=Choice.objects.get(id=choice['id']))
        else:
          c = ChoiceForm(choice)

        if c.is_valid():
          c.save()

    return poll

您需要的是Django Formsets(),特别是:Model Formsets()。 对于您的模型,必须使用内联表单集(对于Choice模型)。 您可以在中找到有关它们的所有信息:

希望这有帮助