Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django static annotation

Tags:

python

django

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

like image 307
Trindaz Avatar asked Aug 28 '10 10:08

Trindaz


1 Answers

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 all available db fields classes.

like image 50
Sven R. Kunze Avatar answered Sep 22 '22 02:09

Sven R. Kunze