Adrian
Adrian

Reputation: 87

python - change dict keys in a queryset of values

I have something like this: model.objets.values('id', 'name') that returns a list of dicts with 'id' and 'name' as the keys. Is there a way that I can pass custom names to those keys? Something like: model.objets.values('id', 'name').column_names('main id', 'name of de thing I want')?

I'm using python + django

Upvotes: 3

Views: 2825

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477617

Yes, you can use named arguments, and make use of F expressions [Django-doc] instead:

from django.db.models import F

Model.objects.values(main_id=F('id'), my_name=F('name'))

In case the "target names" are not valid Python identifiers, you can make use of dictionary unpacking:

from django.db.models import F

Model.objects.values(**{'main_id': F('id'), 'name with spaces': F('name')})

That being said, it is often advisable to use serializers [drf-doc] than using .values() as a way to produce JSON blobs.

Upvotes: 11

Related Questions