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

时间:2015-06-02 00:49:50

标签: 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.IntegerField()

民意调查可以有很多选择 - 每个民意调查的金额会有所不同。我正在努力弄清楚如何通过模型保存民意调查,同时保存其相关的选择。

我知道我必须覆盖我的PollForm中的Save和Clean方法,但之后它会变得复杂。我知道有更多的pythonic / djangoesque方式。我的主要困惑是选择和民意调查之间的关系,因为它只是在一个方向上定义。

此外,我无法弄清楚当使用一组选项更新民意调查时这将如何工作,其中一些选项存在且一些是新的。当然,下面的代码不起作用,但我正在考虑这个问题。我希望在正确的方向上轻推一下!

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

1 个答案:

答案 0 :(得分:0)

你需要的是Django Formsets(https://docs.djangoproject.com/en/1.8/topics/forms/formsets/),特别是:Model Formsets(https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#model-formsets)。 对于您的模型,您必须使用内联formset(对于Choice模型)。 您可以在https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#inline-formsets中找到有关它们的所有信息。

希望这有帮助。

相关问题