wim wim - 3 months ago 15
Python Question

Aliasing the dict keys in a Django QuerySet.values call

>>> ppcs.values('price', 'currency__currency_code')
[{'price': Decimal('562.00'), 'currency__currency_code': u'JPY'}]

When using
, is there a way to alias the key names to something else? For example, rather than the output showing the through-relationship
, how can I make the dict key called 'currency' like in the following output:

>>> keys = ['price', 'currency']
>>> [dict(zip(keys, v)) for v in ppcs.values_list('price', 'currency__currency_code')]
[{'currency': u'JPY', 'price': Decimal('562.00')}]

The problem with the idea above is that I don't want a list (nor a generator object) at this stage, I want the output to remain a
as in the first example.

wim wim

The comment of klasske fully answers this question (thanks) --> https://code.djangoproject.com/ticket/16735

In short, here is the Django 1.8+ solution:

from django.db.models import F
ppcs.annotate(currency=F('currency__currency_code')).values('price', 'currency')

Unfortunately, it's not possible in Django v1.7 or earlier.

I'd have preferred the following syntax as was originally suggested in the ticket, and avoiding the need to import that clunky F object, but no dice.

ppcs.values('price', currency='currency__currency_code')