私はDjangoにかなり慣れていないので、次の問題に遭遇しました。特定のファンドの毎日の価格を保存するモデルFundPriceがあります。これをデータベースから取得して、jsベースのチャートに渡したいと思います。
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})
私のテンプレートでは、{{ fund_prices }}
参照を使用すると、次のような結果が得られます。
[{'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')}]
どういうわけかこの出力をフォーマットできますか?例えば、これらを取り除くためdatetime.date(
、Decimal(
フィールドタイプの指標を?
印刷したいのは次のとおりです。
[{'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'}]
このCast
関数を使用するだけで、式の結果タイプをoutput_fieldからのものにすることができます。
あなたの場合value_date
、price
フィールドとフィールドの両方を次のようにキャストします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})
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加