Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing the dict keys in a Django QuerySet.values call

Tags:

python

django

>>> 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.

like image 807
wim Avatar asked Aug 21 '14 10:08

wim


People also ask

How to lookup dictionary data in Django using key names?

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.

How do I annotate a queryset in Django?

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.

Why can’t we use variable name as key in Django Dictionary?

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.

Does Django support aliasing beyond explicit values?

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.


1 Answers

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')
like image 156
3 revs Avatar answered Sep 18 '22 22:09

3 revs