早安,
我是django的新手,我想问你以下问题。
我在models.py中有两个类:
class Single_Income(models.Model):
income_label = models.CharField(max_length=100, editable=True)
income_jan = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11)
income_feb= MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11)
class Total_Income(models.Model):
total_jan = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11)
total_feb= MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11)
在视图中,我有以下代码:
def ricavi_dalle_vendite(request):
items = Single_Income.objects.all()
if request.method == 'POST':
form = SingleIncomeModelForm(request.POST)
if form.is_valid():
print("Il form è valido")
new_input = form.save()
else :
form = SingleIncomeModelForm()
context= {
"form": form,
'items': items,
}
return render(request, "app/income.html", context)
因此,在web_application(网址为“ app / income.html”)中填写表格,就可以填写Single_Income。现在,我要以这种方式自动填充Total_Income模型(在保存Single_Income模型数据之后):
单次收入:
| ____ Jan ____ | ___ Fab _____ ||
| ____ 100 ___ | _____ 100 ____ |
| ____ 100 ____ | ____ 100 ____ |
总收入:
| ____ 200 ____ | ____ 200 ____ |
答案 0 :(得分:0)
您可以通过调用Total_Income
创建Total_Income
的实例。例如:
from . models import Total_Income, Single_Income
from django.db.models import Sum
def ricavi_dalle_vendite(request):
items = Single_Income.objects.all()
if request.method == 'POST':
form = SingleIncomeModelForm(request.POST)
if form.is_valid():
print("Il form è valido")
new_input = form.save()
# get sums of income_jan and income_feb for all records in Single_Income
data_jan = Single_Income.objects.aggregate(Sum('income_jan'))
data_feb = Single_Income.objects.aggregate(Sum('income_feb'))
jan = data_jan['income_jan__sum']
feb = data_jan['income_feb__sum']
# or, sum the incomes from the form
data_jan = new_input.aggregate(Sum('income_jan'))
data_feb = new_input.aggregate(Sum('income_feb'))
jan = data_jan['income_jan__sum']
feb = data_jan['income_feb__sum']
# create a Total_Income instance
total_income = Total_Income(total_jan=jan, total_feb=feb)
# you must save the instance after creating it if you want it to persist
total_income.save()
context= {
"form": form,
'items': items,
'total_income': total_income
}
return render(request, "app/income.html", context)
现在,您可以像访问total_income
一样访问模板中的items
。