ati
ati

Reputation: 53

Django - queryset output formatting

I am fairly new to Django, ran into the following problem: I have a model FundPrice storing daily prices of particular funds. I would like to retrieve this from a database and pass to a js based chart.

views.py

from django.shortcuts import render
from fundmgmt.models import FundPrice

def fund_details_cards(request):
    fp = list(FundPrice.objects.values('fund_id','value_date','price'))

return render(request,"fundmgmt/fund_detail_cards.html",
              {'fund_prices': fp})

In my template, by using {{ fund_prices }} reference, the result I get is the following:

[{'fund_id': 1, 'value_date': datetime.date(2016, 11, 9), 'price': Decimal('2.574557')}, 
 {'fund_id': 1, 'value_date': datetime.date(2016, 11, 8), 'price': Decimal('2.572507')}, 
 {'fund_id': 1, 'value_date': datetime.date(2016, 11, 7), 'price': Decimal('2.571724')}]

Can I somehow format this output? E.g. get rid of these datetime.date(, Decimal( field type indicators?

What I would like to print is the following:

[{'fund_id': 1, 'value_date': '2016-11-09', 'price': '2.574557'}, 
 {'fund_id': 1, 'value_date': '2016-11-08', 'price': '2.572507'}, 
 {'fund_id': 1, 'value_date': '2016-11-07', 'price': '2.571724'}]

Upvotes: 1

Views: 4026

Answers (1)

Peter Sobhi
Peter Sobhi

Reputation: 2550

You can simply use the Cast function to force the result type of expression to be the one from output_field.

in your case you will cast both value_date and price fields to CharField:

from django.db.models import CharField
from django.db.models.functions import Cast
from django.shortcuts import render

from fundmgmt.models import FundPrice


def fund_details_cards(request):
    fp = list(FundPrice.objects.values('fund_id',
                                       value_date=Cast('value_date', CharField()),
                                       price=Cast('price', CharField())))

    return render(request,"fundmgmt/fund_detail_cards.html",
                  {'fund_prices': fp})

Upvotes: 1

Related Questions