【问题标题】:Django - How to get all items from a model that has foreign key?Django - 如何从具有外键的模型中获取所有项目?
【发布时间】:2020-12-18 12:33:25
【问题描述】:

我正在创建两个模型: 原料配方和配方。这是每个的代码:

原料公式:

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

我怎样才能获得作为配方一部分的所有原料配方?

【问题讨论】:

    标签: python django django-models foreign-keys one-to-many


    【解决方案1】:

    你可以这样做

    首先参考你想要的公式

    f = Formula.objects.get(name = <formula name>)
    

    然后你用它来获取原料公式

    fsf = FeedstockFormulas.objects.filter(formulas = f)
    

    【讨论】:

      【解决方案2】:

      您应该在 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
      

      【讨论】:

        【解决方案3】:

        您可以通过formulas 字段的related_name 访问FeedstockFormulas,在您的情况下默认为feedstockformulas_set

        例如:

        formula = Formulas.objects.first()
        print(formula.feedstockformulas_set.all().feedstock)
        

        【讨论】:

          猜你喜欢
          • 2015-09-19
          • 1970-01-01
          • 2021-01-13
          • 2016-04-26
          • 1970-01-01
          • 1970-01-01
          • 2021-12-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多