やりたいこと
売り上げなどの年次(fiscal_year)データを5年分画面に出力するアプリを作っています。
そこで、2013, 2014, 2015, 2016, 2017, 2018と、6年のデータがあった場合、直近の5年分のデータ(2014~2018)を、古い順に出力したいです。
ご教授いただければ幸いです。
よろしくお願いいたします。
環境
Python 3.6
Django 2.1.0
期待する結果
||2014|2015|2016|2017|2018|
|:--|:--:|:--:|:--:|--:|
|売上高|200|220|210|230|240|
|売上高総利益|120|180|200|180|120|
現在の結果
||2018|2017|2016|2015|2014|
|:--|:--:|:--:|:--:|--:|
|売上高|240|230|210|220|200|
|売上高総利益|120|180|200|180|120|
現在のコード
HTML
1fstatement_list.html 2 3 <div class="table-responsive" style="text-align: right;"> 4 <table width="100%" class="table display nowrap"> 5 <tr> 6 <th>決算日</th> 7 {% for item in fstatement_list %} 8 <th>{{ item.fiscal_year }}</th> 9 {% endfor %} 10 </tr> 11 <tr> 12 <th>総売上高</th> 13 {% for item in fstatement_list %} 14 <td>{{ item.pl_gross_sales|intcomma }}</td> 15 {% endfor %} 16 </tr> 17 <tr> 18 <th>売上高総利益</th> 19 {% for item in fstatement_list %} 20 <td>{{ item.pl_gross_profit|intcomma }}</td> 21 {% endfor %} 22 </tr> 23 </table>
python
1views.py 2class FstatementListView(LoginRequiredMixin, ListView): 3 model = Fstatement 4 5 def get_queryset(self): 6 fstatement_list = Fstatement.objects.filter(company=self.request.user.profile.company).order_by('-fiscal_year')[:5] 7 return fstatement_list
試したこと
reversedを使ってみた
python
1views.py 2class FstatementListView(LoginRequiredMixin, ListView): 3 model = Fstatement 4 5 def get_queryset(self): 6 fstatement_list = Fstatement.objects.filter(company=self.request.user.profile.company).order_by('-fiscal_year')[:5] 7 fstatement_list = fstatement_list(reversed(fstatement_list)) 8 return fstatement_list
(結果)
reversedが使えないとエラー。
リストを再度並び替えた
python
1views.py 2class FstatementListView(LoginRequiredMixin, ListView): 3 model = Fstatement 4 5 def get_queryset(self): 6 fstatement_list = Fstatement.objects.filter(company=self.request.user.profile.company).order_by('-fiscal_year')[:5] 7 fstatement_list = fstatement_list.order_by('-fiscal_year') 8 return fstatement_list
(結果)
Cannot reorder a query once a slice has been taken.
というエラー。

回答4件
あなたの回答
tips
プレビュー