tags:

views:

36

answers:

2

Hi,

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

+1  A: 

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

Car.objects.all().extra(select = {'sales': 0})
Manoj Govindan
Thanks for the quick reply. Works great!
Trindaz
A: 
for car in Car.objects.all()
    setattr(car, 'sales', 0)

this will add to each element in your queryset a field named sales with value 0. This field can only be used with this car instance.

UPDATED

FallenAngel
Thanks for the quick reply, but it didn't work for me. The error: 'QuerySet' object has no attribute 'setattr'
Trindaz
`Setattr` sets the value for the _queryset_, not for _each value in the queryset_. http://docs.python.org/library/functions.html#setattr
Manoj Govindan
Sorry for my mistake, answer is corrected.
FallenAngel
UPDATE: First time around I actually ran car.setattr, which is what caused the error. But Manoj you are correct - this only sets that attribute one time at the queryset level, so doesn't really help me out while iterating cars. --Trindaz on Fedang #django
Trindaz