2016-06-14 35 views
0

我有汽车数据,我希望它们在引导列表组中显示。问题是我想要一个汽车品牌只能显示一次。在Django模板的引导列表组中显示数据

{u'cars': [{u'brand': u'Ford', u'model': u'Focus'}, {u'brand': u'u'Ford', u'model': u'Fiesta'}, {u'brand': u'u'Toyota', u'model': u'Hilux'}] 

我追加列出车views.py:

for i in readable_json["cars"]: 
      cars.append({ 
       'brand': i['brand'], 
       'model': i['model'], 
       }) 

因此,在这个例子中,我想这是这个样子的引导列表组:http://www.bootply.com/XEnAquIInD

NOT LIKE本文: http://www.bootply.com/2YX7PgB1ch

问题在于我在Django模板中。当我使用模板循环汽车时,我需要在HTML中为列表项目设置不同的数据父项ID。另外,我如何检查,显示的车型品牌不超过一次?

<div id="MainMenu"> 
     <div class="list-group panel"> 
      <div href="#demo" class="list-group-item list-group-item-success" data-parent="#MainMenu">Laitteet</div> 
      <div class="collapse in" id="demo"> 

      {% for car in cars %} 

      <a href="#{{ ??? }}" class="list-group-item" data-toggle="collapse" data-parent="#{{ ??? }}">{{ car.brand }} <i class="fa fa-caret-down"></i></a> 

      <div class="collapse list-group-submenu" id="{{ ??? }}"> 
       <a href="#" class="list-group-item" data-parent="#{{ ??? }}">{{ car.model }}</a> 
      </div> 
     {% endfor %} 
     </div> 
    </div> 
</div> 
+2

你不应该这样做的逻辑就像在模板检查的独特性 - 你需要做的是,在你看来和之前过滤数据它传递给模板。添加一个唯一的ID然后变得简单。 – solarissmoke

+0

我应该做两个清单;一个用于汽车,一个用于ID:s? – MMakela

+0

不是。它部分取决于您的数据来自哪里 - 它是否具有唯一的源ID(例如数据库ID?)。如果没有,你可以[slugify](https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.text.slugify)一个独特的领域,如汽车名称。 – solarissmoke

回答

0

我会做这样的事情来清理你的视图中的数据:

cars_seen = set() 
for i in readable_json["cars"]: 
    car_identifier = '{}-{}'.format(i['brand'], i['model']) 
    if not car_identifier in cars_seen: 
     cars.append({ 
      'brand': i['brand'], 
      'model': i['model'], 
      'id': car_identifier, 
     }) 
    cars_seen.add(car_identifier) 

cars现在将包含的独特汽车(假设brand + model是如何定义的唯一性)的列表。

在模板中,你可以再生成唯一ID的东西,如:

<a href="#{{ car.car_identifier|slugify }}">...</a> 
+0

仍然汽车列表可能有多次相同的品牌名称,如:http://www.bootply.com/2YX7PgB1ch,所以标识符不工作应该。 – MMakela

+0

是的 - 如果你按照我的代码说明了这一点。您不会在这里获得现成的解决方案,并需要了解基础逻辑,以便您可以自己实施它。 – solarissmoke