user3437022
user3437022

Reputation: 97

Rename nested annotated field via Django ORM

Is it possible to renaming nested fields using for group by clause?

This query:

paymentitem.objects.filter(payment=p).values('item__vat_tax').annotate(base=models.Sum('price')).order_by('item__vat_tax')

returns expected data:

<QuerySet [{'base': Decimal('41.322'), 'item__vat_tax': 15}, {'base': Dec
    imal('483.470'), 'item__vat_tax': 21}]>

I want to rename field 'item__vat_tax' as 'vat'. This query:

paymentitem.objects.filter(payment=p).extra(select={'vat': 'item__vat_tax'}).values('item__vat_tax').annotate(base=models.Sum('price')).order_by('vat')

return the same result but surprisingly ordered by vat too.

If I change the field name inside the value statement, it raise an error.

Upvotes: 0

Views: 533

Answers (2)

Shariful Islam
Shariful Islam

Reputation: 576

Rename the annotate value name in Django. If we use the Django F expression then easily can solve this.

from django.db.models import F 
paymentitem.objects.filter(payment=p).values(vat=F('item__vat_tax')).annotate(base=models.Sum('price')).order_by('vat')

Return Expected Data

<QuerySet [{'base': Decimal('41.322'), 'vat': 15}, {'base': Decimal('483.470'), 'vat': 21}]>

Upvotes: 0

user3437022
user3437022

Reputation: 97

The solution is to use F expression:

paymentitem.objects.filter(payment=p).values(vat=F('item__vat_tax')).annotate(base=models.Sum('price')).order_by('vat')

Upvotes: 2

Related Questions