見積一覧ページで、sales_estimatesテーブルに入っている各見積りデータを表示させたい。
▼ワイヤーフレーム
機能要件
– 見積の会社名は、hasManyのリレーション関係にあるsales_clientsのnameから引っ張って表示させたい
– 最新の登録順に表示させる
– 見積件数が増えた場合を想定して、ページネーションを実装する
– 見積の合計金額を表示させる
### views.py
– ${model}.object.all()でデータを取得する
– order_by(‘-id’)でidをdescで取得する
– *.count()で対象のレコード件数を取得できる
– *.aggregate(Sum(‘${columnName}’))で対象カラムの合計値を取得できる
1 2 3 4 5 6 7 8 9 10 11 12 13 | from django.db.models import Sum def estimate(request, num = 1 ): data = Estimates.objects. all ().order_by( '-id' ) page = Paginator(data, 3 ) count = data.count() total = data.aggregate( Sum ( 'total' )) params = { 'data' : page.get_page(num), 'count' : count, 'total' : total, } return render(request, 'sales/estimate.html' , params) |
### estimate.html
– sumの値は、view側でも{{total.total__sum}}と書いてあげる必要がある
1 2 3 4 5 | < div class = "row col-md-12" > < label class = "col-form-label col-md-3" >検索結果 {{ count }}件</ label > < label for = "total" class = "col-md-2 col-form-label" >合計見積金額(円)</ label > < input type = "text" disabled id = "total" class = "form-control col-md-4 text-right" value = "{{total.total__sum}}円" placeholder = "" > </ div > |
– 親テーブルの値である会社名を表示させるには、item.client.nameというように、foreignKeyとそのテーブルのカラム名を繋げてあげれば良い
1 2 3 4 5 6 7 8 9 10 11 | {% for item in data %} < tr > < td >{{item.id}}</ td > < td class = "text-nowrap" >{{item.estimate_date}}</ td > < td class = "text-nowrap" >{{item.client.name}}</ td > < td class = "text-nowrap" >{{item.title}}</ td > < td class = "text-right" >{{item.total}}円</ td > < td class = "text-nowrap" >< button class = "btn btn-light" >詳細</ button > < button class = "btn btn-light" >編集</ button > < button class = "btn btn-light" onclick = "location.href='#modal'" >削除</ button ></ td > < td class = "text-nowrap" >< button class = "btn btn-light" >ダウンロード</ button ></ td > </ tr > {% endfor %} |
Djangoの場合、エラー時に参考にする記事の英語の割合が増えるので、やってて面白い。
さて、次は、見積金額を表示させる際に、3桁以上の場合はカンマをつけたいですね。