Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare year and month of date field to be greater than

Tags:

python

django

I'm going to do this query:

today = datetime.date.today()
year=today.year
month=today.month
news=News.objects.filter(date__year__lt = year,date__month__lt=month)

Note:News object has a field named date but I get this error:

Join on field 'date' not permitted. Did you misspell 'year' for the lookup type?

what's your idea?

thanks in advance

like image 558
Asma Gheisari Avatar asked Dec 12 '22 05:12

Asma Gheisari


2 Answers

You can't append __lt onto to __year or __month. Only the last double-underscored bit is consider the qualifier, everything before it is treated as a traversal, i.e. Django will try to look up a field named year on join table named date, which is obviously not correct.

For something like this you'll need to just compare the date directly:

date = datetime.date(year, month, 1)
news = News.objects.filter(date__lt=date)
like image 129
Chris Pratt Avatar answered Feb 11 '23 18:02

Chris Pratt


Django has trouble with certain lookups when working through a relation (e.g. date__year__*). I think this is something they are working on for future versions.

Does this produce an acceptable result?

news = News.objects.filter(date__lt = datetime.date(year, month, 1))
like image 39
aganders3 Avatar answered Feb 11 '23 18:02

aganders3