I'm trying to do an annotation of the queryset based on a DateField as shown.
I am using Django version 1.8.12 and MYSQL version 5.6.40.
Tried following How to annotate a queryset with number of days since creation, but here its a DateTimeField. The comments below says "Changing it to Value(now.date(), DateField()) - F('creation_date__date'), doesn't work"
The Model code is shown below:
class Holding(models.Model):
trans_date = models.DateField(_("Trans. Date"), null=False)
...
And the annotate query that gives the wrong duration is shown below:
today = timezone.now().date()
testqs = Holding.objects.filter(id=1)
myqs = testqs.annotate(duration = ExpressionWrapper( Value(today, DateField()) - F('trans_date'), output_field=DurationField()))
And when i try to print, all I get is None for the duration. Difference printed for reference.
for i in myqs:
print i.duration, '-', today-i.trans_date
None - 1224 days, 0:00:00
None - 1206 days, 0:00:00
None - 1144 days, 0:00:00
None - 1051 days, 0:00:00
None - 1045 days, 0:00:00
I expect the duration to be a timedelta values with the difference between today and trans_date and not None.
DateField
, it returns "9661 days, 0:00:00" when I print theduration
annotation. – SoucyExpressionWrapper
was already supported in Django 1.8, not sure why it shouldn't work for you. But yeah, might be an issue with your specific setup. – Soucyprint(qs.query)
) to see if it's correct. Also as a last resort, write the SQL yourself, that way you can also see if your MySQL is producing strange results and use.raw()
. – SoucySELECT `Portfolio_holding`.`id`, `Portfolio_holding`.`trans_date`, ... (2019-08-21 - `Portfolio_holding`.`trans_date`) AS `duration` FROM `Portfolio_holding` WHERE (`Portfolio_holding`.`id` = 1)
– Abscissa'2019-08-21'
. Try to query directly your db in a mysql shell. – Soucy