Search code examples
pythondjangodrop-down-menuorganization

Django: drop-down list


I have a model 'Post,' which is just a like a blog post:

class Post(models.Model):

Each post has a pub_date attribute:

pub_date = models.DateField()

When displaying posts on my site, I'd like to have an simple, drop-down menu at the top of the page with a structure like:

  • 2014
    • Jan
    • Feb
  • 2013
  • 2012

and so on. I can't figure out how to sort my posts like this with Django, and I think it would be bad practice to hard code it. How would you solve this?


Solution

  • You can use something like:

    posts = Post.objects.all()
    sortedposts = {}
    for p in posts:
        sortedposts.setdefault(p.pub_date.year, {})\
                   .setdefault(p.pub_date.strftime('%b'), [])\
                   .append(p)
    

    Which would give you the structure:

    sortedposts = {
        2014: {
          'Jan': [<post4>, <post3>], 
          'Feb': [<post2>]
        },
        2013: {
          'Jul': [<post1>]
        }
    }