Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"SELECT field as x..." with Django ORM

Tags:

orm

django

Is it possible to use AS sql statement with Django ORM:

SELECT my_field AS something_shiny WHERE my_condition = 1

If it is possible then how?

like image 257
aemdy Avatar asked Apr 07 '12 15:04

aemdy


2 Answers

By now the Django documentation says that one should use extra as a last resort.

So here is a better way to do this query:

from django.db.models import F
Foo.objects.filter(cond=1).annotate(sth_shiny=F('my_field'))
like image 109
Michael Avatar answered Oct 19 '22 14:10

Michael


use extra()

Foo.objects.filter(cond=1).extra(select={'sth_shiny':'my_field'})

Then you could access sth_shiny attr of resulted Foo instances

like image 6
okm Avatar answered Oct 19 '22 14:10

okm