显示带有两个外键的 Django 内联表单集的正确选择文本

发布于 2024-09-07 23:39:37 字数 1133 浏览 1 评论 0原文

我已经成功地使用内联表单集创建了一个配方输入表单,其中包含一个配方表单(只是一个模型表单)和一个 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 = inlineformset_factory(Recipe, RecipeIngredient, extra=1,
            can_delete=False)

一切都运行良好......直到我单击成分下拉菜单,除了“什么也没有看到”对每个成分条目重复“成分对象”选择,而不是我正在寻找的标题值。

有什么方法可以保持这种直接的方法并在下拉列表中显示 Ingredient.title 吗?这在保存、显示等方面还会有其他问题吗?

如果做不到这一点,我需要做什么才能使这项工作成功?

谢谢大家。

I have successfully used inline formsets to create a recipe input form that consists of a Recipe form (just a model form) and a RecipeIngredient formset. The models are:

#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)

I want to change the ingredient to the following:

ingredient = models.ForeignKey(Ingredient)

Where Ingredient is:

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

I left views.py unchanged to set up the inline formset:

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

And everything worked perfectly ... until I clicked the ingredient drop down and saw nothing but "Ingredient object" choices repeated for every ingredient entry rather than the title value I was looking for.

Is there any way to maintain this straight forward approach and display Ingredient.title in the dropdowns? Will this have any other problems wrt saving, displaying, etc.?

Failing that, what do I need to do to make this work?

Thanks all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

还如梦归 2024-09-14 23:39:37

解决方案确实很简单:只需在 Ingredient 模型上定义一个 __unicode__ 方法即可返回 self.title

The solution is indeed trivial: just define a __unicode__ method on the Ingredient model to return self.title.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文