RonLugge RonLugge - 7 months ago 38
Python Question

How do I get each distinct 'year' value out of a Django model with a datetime field?

I can successfully filter by a given year in my Django model, but I'm having trouble finding a way to list valid years so a user can access them.

I have a django model with a defined 'datetime' field, oh-so-originally named 'date'. In my templates, I can successfully access the 'bar.date.date.year' field, so I know it exists, but when I try the following function...

blog_years=[]
for entry in blog_entries:
if entry.date.date.year not in blog_years:
blog_years.append(entry.date.date.year)


I'm told that "'builtin_function_or_method' object has no attribute 'year'"

I can only assume I"m tripping over some aspect of Python I'm not familiar with, but I can't figure out what it is. I'm quite certain it has to be syntactical, but past that...

Answer

The first .date accesses a datetime object.

The second .date is accessing a method on datetime objects that returns a date object but not calling it (this step is unneccessary).

The last part (the way you wrote it) is trying to access the year attribute of the date method, instead of accessing the year attribute of the result of the date method call.

Correcting the code to see the difference, it would look like this...

blog_years=[]
for entry in blog_entries:
    if entry.date.date().year not in blog_years:
        blog_years.append(entry.date.date().year)

But what you should do is more like this...

blog_years=[]
for entry in blog_entries:
    if entry.date.year not in blog_years:
        blog_years.append(entry.date.year)

since datetime objects have the date attribute as well.