简体   繁体   中英

Iterate over queryset in groups of a certain amount

Basically, I want to use a Bootstrap Carousel with a queryset. My question is as to how I should iterate over the queryset so that I can put three objects into a div and then the next three into another div and so on depending on the size of the queryset. See the preudocode below.

{% for group in object_list/3 %}
 <div class="">
  {% for object in group %}
   <p>{{object}}</p>
  {% endfor %}
 </div>
{% endfor %}

You could add a filter called chunks like in this stackoverflow answer :

@register.filter
def chunks(iterable, size):
    iterator = iter(iterable)
    for first in iterator:
        yield chain([first], islice(iterator, size - 1))

and then use the filter in django templates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM