首页 > 解决方案 > 如何在 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在模板内的嵌套中编码什么?

标签: djangodjango-templates

解决方案


您可以使用:

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

推荐阅读