[Fixed]-How to combine querysets in Django to show calendar events?

1👍

I suggest adding a mapping of {day_of_month: events} in your context instead of a list of all events for the whole month. That way, when building your template, you don’t need to iterate over all events for each day of the month.

Here’s a sample implementation:

views.py

from collections import defaultdict

...

def Cal(request, year, month):

    ...

    events = Event.objects.filter(when__year=year, when__month=month)
    event_days = defaultdict(list)
    for event in events:
        event_days[event.when.day].append(event)
    return render(request, "cal/calendar.html", {
                                            "month_cal": month_cal,
                                            "prev_month": prev_month,
                                            "next_month": next_month,
                                            "prev_year": prev_year,
                                            "next_year": next_year,
                                            "event_days": event_days,
                                        })

Next, you’ll need to include a dict lookup template filter in your project. (See linked question for the implementation.)

Now, as you’re looping through your calendar, you can easily access the events by day:

calendar.html

...

{% for week in month_cal %}
    <tr>
    {% for day in week %}
        <td>
            {% if day == 0 %}
                -
            {% else %}
                {{ day }}
                {% for event in event_days|get_item:day %}
                    {# format the event here #}
                    {{ event.description }} 
                {% endfor %}
            {% endif %}
        </td>
        {% endfor %}
    </tr>
{% endfor %}

...
👤keithb

Leave a comment