Split Django Queryset in template for Bootstrap Carousel

瘦欲@ 提交于 2019-12-25 02:57:25

问题


I have a model Banner with fields image and name. I need data from this model to be displayed in groups of three on a moving Bootstrap carousel.

My current implementation is the most expensive and simple one I could think of.

banner1 = Banners.objects.filter(id__exact=1) repeated for 9 entries in the Model.

My question is that is it possible to split one queryset Banners.objects.all() into the three groups of three entries and then how would I go about displaying the three groups across three different slides of the Bootstrap Carousel?


回答1:


This seems like a good place to use the django divisibleby filter. Since you need to add the extra grouping info every three instances, it could look something like this (very abstractly, since I don't know your specific template demands):

{% for banner in banners %}
{% if forloop.counter0|divisibleby:"3" %}
<!-- your carousel wrapping code here -->
{% endif %}
<!-- code for each individual banners here -->
{% if forloop.counter0|divisibleby:"3" %}
<!-- rest of your carousel wrapping code here -->
{% endif %}

where banners would be a context variable that contains Banners.objects.all()



来源:https://stackoverflow.com/questions/24600885/split-django-queryset-in-template-for-bootstrap-carousel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!