開発環境
- Python 3.6.5
- Django 2.1.2
直面している問題
次のようなモデルを作って、利用しています。
python
1from django.db import models 2 3# Create your models here. 4class Money(models.Model): 5 use_date = models.DateField('日付') 6 detail = models.CharField(max_length=200) 7 cost = models.IntegerField(default=0) 8 category = models.CharField(max_length=10) 9 10 def __str__(self): 11 return self.detail + ' ¥' + str(self.cost) 12
ビューを作るときにここからデータをとってこようと考えています。問題が生じているのは、特定の月の支出の合計額をデータベースから計算するコードです。
python
1def index(request, year=TODAY[0], month=TODAY[1]): 2 money = Money.objects.filter(use_date__year=year, 3 use_date__month=month).order_by('use_date') 4 total = 0 5 for m in money: 6 total += m.cost 7#...
これだとうまくいきます。しかし合計額を計算する部分を関数として抽出すると途端にエラーが出てしまいます。
python
1def calc_month_pay(money): 2 total = 0 3 for m in money: 4 total += m.cost 5 6 return cost 7 8 9def index(request, year=TODAY[0], month=TODAY[1]): 10 money = Money.objects.filter(use_date__year=year, 11 use_date__month=month).order_by('use_date') 12 total = calc_month_pay(money) 13 14#...
bash
1NameError: name 'cost' is not defined
なぜでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。