问题
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