django - 如何在 Django 模板中循环“添加”标签?
问题描述
我想计算Product
每个Market
. 现在我只能计算Product
每个Distributor
. 我正在考虑使用“添加”内置模板标签来总结Product
每个模板的变化Distributor
来解决这个问题,但不知道如何在模板for
循环中实现这个。或者有没有更好的解决方案?我愿意接受建议。
我在 Django 中的 5 个相关模型:
class Market(models.Model, RecordStatus):
name = models.CharField(max_length=100)
class Country(models.Model):
market = models.ForeignKey(Market, on_delete=models.SET_NULL, null=True, blank=True)
name = models.CharField(max_length=100)
class Distributor(models.Model, RecordStatus):
headquarter = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True)
name = models.CharField(max_length=100, null=True, blank=True)
class Product(models.Model, RecordStatus):
video = models.URLField(verbose_name='Video URL', max_length=250, null=True, blank=True)
class ProductStock(models.Model):
distributor = models.ForeignKey(Distributor, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
stock = models.PositiveIntegerField(null=True, blank=True)
我的views.py
:
def market_list_view(request):
markets = Market.objects.all()
context = {
'market_list': markets,
}
return render(request, 'product_visualizers/market_list.html', context)
market_list.html
我目前对模板的尝试:
{% for market in market_list %}
<h3>{{market.name}}</h3>
<p>{% for country in market.country_set.all %}
{% for distributor in country.distributor_set.all %}
{{ distributor.productstock_set.all|length }} # should I write |add besides |length to sum the numbers?
{% endfor %}
{% endfor %}</p>
{% endfor %}
我应该for
在模板内的嵌套中编码什么?
解决方案
您可以使用:
class Market(models.Model, RecordStatus):
name = models.CharField(max_length=100)
def get_product_variations(self):
return Product.objects.filter(productstock__distributor__country__market=self).count()
并为您的模板:
{% for market in market_list %}
<h3>{{market.name}}</h3>
<p>Product variations: {{ market.get_product_variations }}</p>
{% endfor %}
推荐阅读
- highcharts - highcharts splinarea 内的异常梯度
- javascript - 我可以在 Switch 语句上使用对象吗?
- jquery - 如何知道 jQuery 中更改的输入值
- python - JunOS pyEz - 将“串行”模式与设备类一起使用会引发异常
- html - Javascript 延迟不适用于 FilePond
- vue.js - 如何在父子组件之间绑定数据
- javascript - Restful Web Services 到 HTML 表
- python - 检查它是否是直角三角形
- c++ - 将对象向量与 int 类型的向量进行比较
- c# - RestSharp 不反序列化所有值