'Django template - combining a loop within a loop and sorting by date

I have an array called Events.

Within the Events array I have another array called Recurrences, using the Django-Recurrences library.

I get the events context from my view as well as today's date and an end date:

context['events'] = PartnerEvents.objects.filter(partner=context['partner'])
context['today'] = datetime.combine(timezone.now().date(), time(0, 0))
context['end'] = context['today'] + timedelta(days=21)
return context

I then loop it out in my template as follows.

{% for e in events %}
            {% for ts in e.recurrences.occurrences %}
               {% if ts >= today and ts <= end %}
                    <p>{{ts|date:'d F'}}</p>
               {% endif %}
            {% endfor %}
            {% endfor %}

It would then display all the events and occurrences, that will take place today and the next 21 days, eg

05 March
07 March
08 March
09 March
10 March
11 March
12 March
14 March
15 March
16 March
17 March
18 March
19 March
21 March
22 March
23 March
24 March
25 March
05 March
12 March
19 March

However, since certain 'partners' can have more than 1 event on a day, it's causing the the other event to only be looped after the specific event. As you'll notice 05 March, 12 March, 19 March which is another "event" only occurring on certain days.

Ideally, it would be nice to have the dates merged and ordered together, eg 5 March, 5 March, 7 March. I'm not sure if that approach should be done in the view logic, or the Template logic.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source