>>> ppcs.values('price', 'currency__currency_code')
[{'price': Decimal('562.00'), 'currency__currency_code': u'JPY'}]
When using QuerySet.values
, is there a way to alias the key names to something else? For example, rather than the output showing the through-relationship currency__currency_code
, 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 ValuesQuerySet
as in the first example.
In your Django template page.html you can lookup dictionary data by directly using key names. 2. Lookup using Variable as Key However, if you want to lookup dictionary values using a variable as key name then you cannot use the above notation.
Each argument to annotate () is an annotation that will be added to each object in the QuerySet that is returned. The aggregation functions that are provided by Django are described in Aggregation Functions below. Annotations specified using keyword arguments will use the keyword as the alias for the annotation.
This is because in Django you need to use a literal string such as “a”, or “b” as key when you lookup a dictionary in Django template. You cannot use a variable name as key.
Following the further discussion on django-developers, I think the consensus is not to support aliasing beyond an explicit .values (alias=F ('field')) as supported since #25871 was fixed. I'm therefore updating this to wontfix.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With