1

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'}]
3
  • You should probably use serializers here: docs.djangoproject.com/en/2.0/topics/serialization/… Commented Feb 20, 2018 at 23:22
  • Are you looking for format in a Django template or to serialize to JSON for JavaScript? Commented Feb 20, 2018 at 23:52
  • indeed, the idea is that I pass data for JavaScript to create chart, in this particular case with morris.js. Commented Feb 21, 2018 at 10:14

1 Answer 1

1

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})
Sign up to request clarification or add additional context in comments.

2 Comments

It does not seem to work.. returns with ValueError: Exception Value: The annotation 'value_date' conflicts with a field on the model.
It worked with the following syntax: values_list(Cast('value_date', CharField()), flat=True))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.