django static annotation

Question:

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

Asked By: Trindaz

||

Answers:

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})
Answered By: Manoj Govindan

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(), …)

Answered By: Sven R. Kunze
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.