使用formset显示和验证多对多关系

时间:2012-09-10 13:21:28

标签: python django django-models django-forms

我有以下数据库架构

class Ingredient(models.Model):
  title = models.CharField(max_length=255)

class Recipe(models.Model):
  # Many more fields that aren't important
  # ...
  ingredients = models.ManyToManyField(Ingredient, through='Measurement',
                                       blank=True, null=True)

class Measurement(models.Model):
  recipe     = models.ForeignKey(Recipe)
  ingredient = models.ForeignKey(Ingredient)
  amount     = models.CharField(max_length=255)

现在我想将其显示为内嵌

<!-- fields that are not important -->

<input type="text" name="ingredient" value="">
<input type="text" name="amount" value="">

因此,当用户输入文本框成分和数量时,它会将新条目保存到Ingredient表中,并使用其id作为测量表。另外,我需要在Recipe表中保存一些附加信息,例如过程和配方标题。我如何实现这种行为?

1 个答案:

答案 0 :(得分:1)

了解formsetsmodelformsets。你可以使用类似的东西:

formset = modelformset_factory(Measurement)

警告如果有很多配方和成分,那么为每个表单呈现成分和配方的选择将会很慢。一个简单的解决方案是使用autocomplete app

django-autocomplete-light示例:

autocomplete_light.register(Ingredient, search_fields=['title'])
autocomplete_light.register(Recipe)

formset = modelformset_factory(Measurement, 
    form=autocomplete_light.modelform_factory(Measurement))