如何根据Django模板中的对象值来迭代值

时间:2019-07-04 17:12:37

标签: django python-3.x django-models django-templates django-views

我有一个“ Saloon”类的模型。我想根据容量的值来迭代轿车名称。我尝试了许多答案( forloop.counter,自定义模板标签和过滤器),但无法做到这一点。

我只想根据容量值重复轿车的建筑和名称

models.py

class Saloon(models.Model):
    building= models.CharField(max_length=55)
    name= models.CharField(max_length=125)
    capacity= models.IntegerField()

views.py

from django.shortcuts import render
from .models import Saloon

def salonogrenci(request):
    saloons = Saloon.objects.all()
    return render(request, 'salonogrenci/home.html', {'saloons':saloons })

home.html

<table class="table table-hover">
  <tbody>
     {% for saloon in saloons %}
        {% for i in range(saloon.kapasite) %}
           <tr>
              <th scope="row">{{ saloon.building }}</th>
              <td>{{ saloon.name }}</td>
           </tr>
        {% endfor %}
     {% endfor %}
   </tbody>
</table>

示例:

Saloon building: 'AA'
Saloon name:'ABC'
Saloon capacity:3

Saloon building: 'BB'
Saloon name:'EDF'
Saloon capacity:2

表将与html文件中的一样

AA ABC
AA ABC
AA ABC
BB EDF
BB EDF

1 个答案:

答案 0 :(得分:1)

视图侧实施此逻辑可能更有意义。例如,通过使用列表理解功能,该函数将多次生成包含Saloon对象的列表:

def salonogrenci(request):
    saloons = [s for s in Saloon.objects.all() for __ in range(s.capacity)]
    return render(request, 'salonogrenci/home.html', {'saloons':saloons })

然后,您可以简单地遍历saloons变量并分别渲染行,例如:

<table class="table table-hover">
  <tbody>
     {% for saloon in saloons %}
       <tr>
          <th scope="row">{{ saloon.building }}</th>
          <td>{{ saloon.name }}</td>
       </tr>
     {% endfor %}
   </tbody>
</table>