如何在Django模板中循环'add'标签?

时间:2019-12-11 10:36:50

标签: django django-templates

我想计算每个Product中有多少Market个可用版本。目前,我只能计算每个Product的{​​{1}}变化。我正在考虑使用'add' built-in template tag对每个Distributor中的Product变化求和以解决此问题,但不知道如何在模板Distributor循环中实现。还是有更好的解决方案?我愿意征求意见。

我在Django中的5个相关模型:

for

我的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 %} 中编码什么?

1 个答案:

答案 0 :(得分:2)

您可以使用:

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 %}