Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Distinct Years and Months for Django Archive Page

I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this

2009 - Jan, Feb, Mar
2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
2007 - Sep, Oct, Nov, Dec
like image 855
Apreche Avatar asked Mar 24 '09 19:03

Apreche


People also ask

How do I get distinct in Django?

distinct() Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results. By default, a QuerySet will not eliminate duplicate rows.

What is QuerySet?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What filter returns in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is exclude in Django ORM?

The exclude() method from the QuerySet class returns all objects that do not match the given keyword arguments. So whatever data matches the parameter that is passed into the exclude() method will be excluded from the returned QuerySet.


2 Answers

This will give you a list of unique posting dates:

Posts.objects.filter(draft=False).dates('post_date','month',order='DESC')

Of course you might not need the draft filter, and change 'post_date' to your field name, etc.

like image 78
Van Gale Avatar answered Oct 19 '22 08:10

Van Gale


I found the answer to my own question.

It's on this page in the documentation.

There's a function called dates that will give you distinct dates. So I can do

Entry.objects.dates('pub_date','month') to get a list of datetime objects, one for each year/month.

like image 28
Apreche Avatar answered Oct 19 '22 08:10

Apreche