Search code examples
djangodjango-querysetdjango-annotate

Annotate with a static date - Django


I'm trying to annotate a queryset with a static date in Django.

With an integer (instead of a date) it works:

from django.db.models import Value, IntegerField

cars= Car.objects.all().annotate(sales=Value(0, IntegerField()))

How can I make it works with date??

from django.db.models import Value, DateField

cars= Car.objects.all().annotate(mydate=Value('2019-01-01', DateField()))

Solution

  • You can use Cast

    cars= Car.objects.annotate(sales=Cast(Value('20190101'), output_field=DateField()))