![](/img/trans.png)
[英]How to get all objects referenced as ForeignKey from given field in a module in django
[英]How to sum all integer properties from ForeignKey objects in django template?
在我的模型中,每个产品都有变体,并且每个变体都有orderitem
。 每个orderitem
都有一个整数值,即数量。
Django模板中是否有一种方法可以添加特定产品的所有数量并显示出来?
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(decimal_places=2, max_digits=12)
store = models.ForeignKey(Store)
class Variation(models.Model):
product = models.ForeignKey(Product)
title = models.CharField(max_length=255)
active = models.BooleanField(default=True)
stock = models.PositiveIntegerField(null=True, blank=True)
deleted = models.BooleanField(default=False)
class Orderitem(models.Model):
variation = models.ForeignKey(Variation)
quantity = models.PositiveIntegerField() # I want to display the sum of this
order = models.ForeignKey(Order)
有几种方法。
1-product.get_total_order()如果要在某处重用它,则可以在模型中添加一个方法:
class Product(models.Model):
...
def get_total_order(self):
return ...
并显示在模板中:
{{ product.get_total_order }}
2.在视图中,如果您从不重复使用该信息:
def your_view(request, ...):
return render(request, template_name...html, {'total_order': xxx})
模板:
{{ total_order }}
3.作为模板标签如果您要重复使用它,但是您不喜欢第一个选项(使模型保持明亮),则可以添加一个过滤器标签:
{{ product|product_total_order }}
注释/评论:
related_name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.