Reputation: 1169
I have a list of years. And I want to filter objects that belong to specific years:
begYears = [2012, 2013, 2014]
#dateTime field's name is 'beginning_date'. This code does not work...
works = Work.objects.filter(beginning_date__year__in=begYears)
Upvotes: 1
Views: 971
Reputation: 10697
Runtime generation of the filter criteria (begYears may not be hard coded, but deducted in real life):
begYears = [2012, 2013, 2014]
q = Q()
for begYear in begYears:
q.add(Q(beginning_date__year=begYear), Q.OR)
works = Work.objects.filter(q)
Upvotes: 0
Reputation: 734
Django 1.6 doesn't support nested lookups, that is year__in isn't possible. In 1.7 nested lookups are supported, but year__in isn't implemented in 1.7. It is likely addition to 1.8. For now the Q-approach is the way to go.
Upvotes: 1
Reputation: 2694
There is definitely a nicer solution than this (writing a property that renders the year and using that? using the dates() filter?), but I can't think of it right now:
works = Work.objects.filter(
Q(beginning_date__year=2012)|
Q(beginning_date__year=2013)|
Q(beginning_date__year=2014)
)
Upvotes: 2