django : How to write alias in queryset

Viewed 17679

How can one write an alias for the column name in django query set. Would be useful for union-style combinations of two linked field to the same foreign model (for instance).

for example in mysql :

select m as n, b as a from xyz

how can i do this in django query set ?

models.Table.objects.all().values('m', 'b')

Any help really appreciate it.

5 Answers

You can annotate the fields as you want, with the F expression:

from django.db.models import F

models.Table.objects.all().values('m', 'b').annotate(n=F('m'), a=F('b'))
Related