Home > Software design >  How to display the latest 3 items in django
How to display the latest 3 items in django

Time:11-18

Is there a way to query django model to display the latest 3 items in a section of my template and display the next 3 on the next part of my template in order? for example: some_list is ['a', 'b', 'c','d', 'e', 'f', 'g'], so [:3] gives you ['a','b','c'] so how do i get the next 3 from 'd' to 'f' in my query?

CodePudding user response:

Yes.

If you're passing in an object_list in the context data, you can do something like this.

{% for o in object_list|slice:":3" %}
    {{ o }}<br>
{% endfor %}

<section>
Miscellaneous HTML Stuff
</section>

{% for o in object_list|slice:"3:6" %}
    {{ o }}<br>
{% endfor %}

If you don't have object_list in your context, then you can either add it or create two separate context variables with the data you are looking for.

class MyView(ListView):
    model = MyModel

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['list1'] = MyModel.objects.all()[:3]
        context['list2'] = MyModel.objects.all()[3:6]
        return context

And your template would loop through list1 and list2 instead of object_list.

  • Related