python - 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?
解决方案
您应该在 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
推荐阅读
- winforms - Cefsharp Winform 显示图像模糊
- scheme - 了解序列的工作原理
- mongodb - 如何从包含多个项目的项目价格集合中计算最接近的总价格
- azure-devops - TF400324: Azure DevOps 服务不可用
- reactjs - 从获取请求 React Native 中渲染数据
- swift - 对属性使用 getter/setter 使其不会出现在反射(镜像)中
- ruby-on-rails - 防止使用 Rails 处理请求
- c# - Unity - 使用 C#(无着色器)在网格上投影纹理
- find - 在bash中合并两个类似的目录
- windows - 为什么我的按钮功能执行我的win32项目的onload?C++