比萨饼有浇头,顶部有制造商,制造商有名字。我们假设同一制造商创建所有浇头。
我可以通过以下查询获得制造商的价值:
pizza.toppings.all()[0].manufacturer.name
这是基于这样的模型:
class Pizza(models.Model):
pizza = models.ManyToManyField(Topping)
class Topping(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
class Manufacturer(models.Model):
name = models.CharField(max_length=255)
然而,查询中的all()[0]
似乎很难看。有没有办法重写上面的查询,所以它看起来像这样:
pizza.toppings.manufacturer.name
我知道有多个浇头,所以查询不能这么简单,但all()[0]
似乎很糟糕。
感谢您的建议。
答案 0 :(得分:1)
如果同一制造商创建了所有浇头,请将manufacturer
关系放在Pizza
模型中。因此,您可以像pizza.manufacturer.name
更新(因为您说您无法更改模型):
from django.utils.functional import cached_property
class Pizza(models.Model):
pizza = models.ManyToManyField(Topping) # this should be called toppings, not pizza
@cached_property
def manufacturer(self):
topping = self.pizza.toppings.first()
if topping:
return topping.manufacturer
现在您可以像pizza.manufacturer
答案 1 :(得分:1)
而不是
pizza.toppings.all()[0].manufacturer.name
你实际上可以做到
pizza.toppings.first().manufacturer.name
这将返回第一个顶部
的制造商名称