53

I want to add a static value to the results of a database query using django (so not using 'raw' SQL)

For example, if I have an object Car with fields make, model, and color, then I want my results set with extra static value to look something like this:

make     model     color    sales
----     -----     -----    -----
nissan   bluebird  black    0
ford     fiesta    red      0
toyota   camry     green    0

I tried code like

cars= Car.objects.all().annotate(sales=0)

but got errors. What can I do?

Cheers, Dave

--Trindaz on Fedang #django

Trindaz
  • 17,029
  • 21
  • 82
  • 111

2 Answers2

133

Django features Value expressions:

from django.db.models import Value

cars= Car.objects.annotate(sales=Value(0))

Prior to Django 3.2, specify the field class:

from django.db.models import Value, IntegerField

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

Instead of IntegerField() you can use instances of all available model fields (ex: CharField(), ...)

Sławomir Lenart
  • 7,543
  • 4
  • 45
  • 61
Sven R. Kunze
  • 1,909
  • 2
  • 13
  • 17
  • 3
    This is actually the better answer now. extra() is going to be, if not already deprecated. – Trent Jul 31 '18 at 04:01
  • When I use this approach (in Django 3.0) I find the `sales` column is being filled with `None` instead of `0` – Dylan Nov 07 '19 at 03:57
  • 1
    This works for me in Django 3.2, simply using `.annotate=Value(0)`. – caram Mar 12 '21 at 13:37
16

Update

This solution uses soon-to-be-deprecated API. See this answer for a better way to solve this.

Original Answer

You can use the extra() method. Like this:

Car.objects.all().extra(select = {'sales': 0})
Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
  • 2
    "This is an old API that we aim to deprecate at some point in the future" https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.extra – Benoit Blanchon Feb 14 '20 at 17:13