0

我有以下数据库架构

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="">

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

4

1 回答 1

1

Learn about formsets and modelformsets. You can use something like:

formset = modelformset_factory(Measurement)

Warning if there is a lot of recipes and ingredients, then rendering the select for ingredient and recipe for each form will be slow. A simple solution is to use an autocomplete app.

Example with django-autocomplete-light:

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

formset = modelformset_factory(Measurement, 
    form=autocomplete_light.modelform_factory(Measurement))
于 2012-09-10T13:37:11.930 回答