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

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

SELECT my_field AS something_shiny WHERE my_condition = 1

If possible, how?

+3


source to share


2 answers


use extra ()

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

      



Then you can access sth_shiny

attr from the given Foo instances

+3


source


Currently the Django documentation says to be used as a last resort .

So, here's the best way to make this request:



from django.db.models import F
Foo.objects.filter(cond=1).annotate(sth_shiny=F('my_field'))

      

+6


source







All Articles