[英]Django - How to get all items from a model that has foreign key?
I'm creating two models: Feedstockformula and formula.我正在创建两个模型:Feedstockformula 和 formula。 This is the code for each one:
这是每个代码:
FeedstockFormula:原料配方:
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="")
Formula:公式:
from django.db import models
class Formulas(models.Model):
name = models.CharField(max_length=100)
cost = models.FloatField()
weight = models.FloatField()
How can I get all the FeedstockFormulas that is part of a Formula?我怎样才能获得作为配方一部分的所有原料配方?
You should add "related_name" to formulas field in FeedstockFormulas.您应该将“related_name”添加到 FeedstockFormulas 中的公式字段。
Like this:像这样:
formulas = models.ForeignKey("dashboard.Formulas", related_name="feed_stock_formulas",on_delete=models.CASCADE, default="")
Django use reverse relation on ForeignKey, you can access all FeedstockFormulas that is part of a Formula by writing this: Django 在 ForeignKey 上使用反向关系,您可以通过编写以下代码访问作为公式一部分的所有 FeedstockFormulas:
Formulas.feed_stock_formulas
You can access the FeedstockFormulas
via the related_name
of your formulas
field, which defaults to feedstockformulas_set
in your case.您可以通过
formulas
字段的related_name
FeedstockFormulas
在您的情况下默认为feedstockformulas_set
。
For example:例如:
formula = Formulas.objects.first()
print(formula.feedstockformulas_set.all().feedstock)
You could do it like this你可以这样做
First get a reference to the formula you want with something like首先参考你想要的公式
f = Formula.objects.get(name = <formula name>)
Then you use it to get the feedstockformulas然后你用它来得到原料配方
fsf = FeedstockFormulas.objects.filter(formulas = f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.