首页 > 解决方案 > Django - 如何从具有外键的模型中获取所有项目?

问题描述

我正在创建两个模型:Feedstockformula 和 formula。这是每个人的代码:

原料配方:

from django.db import models

class FeedstockFormulas(models.Model):
    ratio = models.FloatField()
    feedstock = models.OneToOneField("dashboard.Feedstock", on_delete=models.CASCADE, default="0")
    formulas = models.ForeignKey("dashboard.Formulas", on_delete=models.CASCADE, default="")

公式:

from django.db import models

class Formulas(models.Model):
    name = models.CharField(max_length=100)
    cost = models.FloatField()
    weight = models.FloatField()

如何获得作为配方一部分的所有 FeedstockFormulas?

标签: pythondjangodjango-modelsforeign-keysone-to-many

解决方案


您应该在 FeedstockFormulas 的公式字段中添加“related_name”。

像这样:

formulas = models.ForeignKey("dashboard.Formulas", related_name="feed_stock_formulas",on_delete=models.CASCADE, default="")

Django 在 ForeignKey 上使用反向关系,您可以通过编写以下代码来访问作为公式一部分的所有 FeedstockFormulas:

Formulas.feed_stock_formulas

推荐阅读