Djangoで、会社の得意先月別売上表を作成したいです。
下記の表のように、得意先別、月別の売上高を表した表形式の表示をしたいです。このような表を作る時、どのようにデータを渡したら良いか、分かりません。
現状のviews.pyは、下記のとおりです。
python
1# views.py 2month_list = ['2018.1月', '2018.2月', '2018.3月'・・・] # 実際はこのmonth_listを作るためのコードがありますが、ここでは単純化のためハードコーディングしたものとしています。 3sales = Sales.objects.all() # 売上高モデルの全データ 4customers = Custmer.objects.all() 5for customer in customers: 6 sales = Sales.objects.filter(customer=customer) # 得意先別売上高をピックアップ 7 month_sales_list = [] # 各月の売上を入れるための空のリスト 8 for month in month_list: 9 month_sales = sales.filter(date__range=(month.start_date, month.end_date)) # 月別売上高をピックアップ 10 month_sales_list.append(month_sales) # 2018.1月売上、2018.2月売上、… 11 12 # ここで、customerにmonth_listというアトリビュートを持たせることができれば解決するのではないかと思います。 13 14template = loader.get_template('test/sales.html') 15context = { 16 'month_list': month_list, 17 'customers': customers 18} 19return HttpResponse(template.render(context, request))
上記のmonth_listには、start_date、end_dateというattributeがあります。例えば2018.1月にはstart_date:2018.1.1、end_date:2018.1.31というデータが入っています。
テンプレートは、下記のとおり作っています。
html
1<!--sales.html--> 2<table> 3 <tr> 4 {% for month in month_list %} 5 <th>{{month}}</th> 6 {% endfor %} 7 </tr> 8 {% for customer in customers %} # 得意先毎にループを回します。 9 <tr> 10 <td>{{customer.name}}</td> # 得意先名 11 {% for month_sales in customer.month_sales_list %} 12 <td>{{month_sales.amount}}</td> # 月毎にループを回します。 13 </tr> 14 {% endfor %} 15</table>
上記のviews.pyにおいて、month_listというアトリビュートをcustomerに持たせることができれば、うまく動くのかと思いますが、どうしたらそれができるか、分かりません。
もしくは、このような時一般的に取られる方法やもっと良い方法があれば、教えて頂きたいです。
よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー