Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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...

like image 264
RonLugge Avatar asked Apr 18 '12 17:04

RonLugge


1 Answers

Django has an elegant and efficient way of doing this. You can check from their docs https://docs.djangoproject.com/en/3.0/ref/models/querysets/#dates But to go over it

Entry.objects.dates('pub_date', 'year')

This will bring out distinct year values in the query.

like image 156
kophygiddie Avatar answered Oct 13 '22 22:10

kophygiddie