I have a model configuration as below,
class Foo(models.Model):
start = models.DateTimeField()
end = models.DateTimeField()
How can I retrieve Foo instances with same Year?
Unsuccessfull try:
from django.db.models import F
Foo.objects.filter(start__year=F('end__year'))
returnd empty QuerySet
The SQL query of
Foo.objects.filter(start__year=F('end__year'))statement is,See..? The comparison takes place between the integer (the extracted
start year) and datetime (end datetime)So, Django returned empty
QuerySet.What's the solution?
We could use
ExtractYear()db function to extractYearfromDateTimeFieldand useannotate()function to store it tempoparily. Then compare the annotated field against the year lookup.SQL query: