[Django]-Django's YearArchiveView generic date view

2👍

TLDR; make_object_list returns all the objects for a given YearArchiveView in the view context under object_list. By default make_object_list is False which will result in the returned context object_list being empty.

So the django documentation is a little tricky to understand on this part. But hopefully this helps (tip: looking at the source code really helps).

The YearArchiveView will by default return in the context the following:

  • date_list: A date queryset returning all the months which have objects in them.
  • year: a date object for the given year.
  • next_year: a date object for first day of the next year.
  • previous_year: a date object for the first day of the previous year.

You will notice in this list that the queryset objects for a given year whilst returned are empty.

make_object_list
So from above we know that the context by default will return a number of values relating to the dates of objects the, current year, previous and next but no actual queryset objects from the database.

Setting make_object_list to be true in the YearArchiveView, will result in all the queryset objects for a given year being passed back through the context so they can be used in the view.

Within the template the queryset objects will be available under the context object_list.

When in the template for a given YearArchiveView,you can then use:

{% for item in object_list %}
    <strong>item.title</strong> - {{ item.date }}
{% endfor %}

1👍

In addition to @MattWritesCode reply I would say that there are use cases where you are only interested in building a navigation and not including much of the actual objects.

I imagine dealing with 1000s of articles, like big newspapers do. I would most likely want to display the actual contents in a separate view that supports paging (and maybe fine-grained permission-access, e.g. public posts and posts behind a paywall).

Good question though, I am just speculating about this. Since querysets are lazy I wouldn’t expect it to be a big performance gain, but maybe in some way that is an aspect too. Would be interested in more opinions about it.

👤sthzg

Leave a comment