使用两个外键显示Django内联formset的正确选择文本

时间:2010-07-04 03:52:45

标签: django inline-formset

我已经成功使用内联表单集来创建一个包含Recipe表单(只是一个模型表单)和一个RecipeIngredient表单集的配方输入表单。模型是:

#models.py
class Recipe(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    directions = models.TextField()

class RecipeIngredient(models.Model):
    quantity = models.DecimalField(max_digits=5, decimal_places=3)
    unit_of_measure = models.CharField(max_length=10, choices=UNIT_CHOICES)
    ingredient = models.CharField(max_length=100, choices=INGREDIENT_CHOICES)
    recipe = models.ForeignKey(Recipe)

我想将原料更改为以下内容:

ingredient = models.ForeignKey(Ingredient)

成分是:

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

我保持views.py不变以设置内联formset:

FormSet = inlineformset_factory(Recipe, RecipeIngredient, extra=1,
            can_delete=False)

一切都运作得很完美......直到我点击了成分下拉,只看到“成分对象”选项重复每个成分条目而不是我想要的标题值。

有没有办法保持这种直接的方法并在下拉列表中显示Ingredient.title?这会在保存,显示等方面有任何其他问题吗?

如果做不到这一点,我需要做些什么来完成这项工作?

谢谢大家。

1 个答案:

答案 0 :(得分:2)

解决方案确实微不足道:只需在Ingredient模型上定义__unicode__方法即可返回self.title

相关问题