from django.contrib.auth.models import Permission, User
from django.db import models
from django.utils import timezone
class Movement(models.Model):
startDate = models.DateField(default=timezone.now)
recordTime = models.DateTimeField(default=timezone.now)
endDate = models.DateField(max_length=50)
purpose = models.CharField(max_length=250)
location = models.CharField(max_length=250)
noOfDays = models.IntegerField
vehicleType = models.CharField(max_length=100)
bookingStatus = models.CharField(max_length=250)
done = models.BooleanField(default=False)
cancelled = models.BooleanField(default=False)
def __dir__(self):
return self.location + '|' + self.done + '|' + self.cancelled
class Report(models.Model):
createdOn = models.DateField(default=timezone.now)
SubmittedOn = models.DateField(default=timezone.now,
null=True,blank=True)
userName = models.CharField(max_length=250)
weekNo = models.CharField(max_length=20)
location = models.CharField(max_length=100)
projectCode = models.CharField(max_length=100)
totalAmount = models.FloatField(max_length=300, default=0)
flatsComment = models.CharField(max_length=300, default="")
financeComment = models.CharField(max_length=300, default="")
def __str__(self):
return self.userName + '|' + self.location + '|' + self.weekNo
class Expense(models.Model):
report = models.ForeignKey(Report, on_delete=models.CASCADE)
date = models.DateField(default=timezone.now)
item = models.CharField(max_length=250)
unit = models.CharField(max_length=20)
unitPrice = models.FloatField(max_length=100)
quantity = models.FloatField(max_length=100)
total = models.FloatField(max_length=250)
#views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.db.models import Avg, Count, Min, Sum
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.views import generic
from .models import *
from .forms import *
# Create your views here.
def programme(request):
return render(request, 'prog/prog.html', {})
def create_report(request):
form = ReportForm(request.POST or None, request.FILES or None)
object_list = Report.objects.all()
if form.is_valid():
report = form.save(commit=False)
report.save()
expense.save()
report.totalAmount = Expense.objects.aggregate(Sum('espence_total'))
return redirect('prog:reports')
else:
context = {
'form': form,
'object_list': object_list
}
return render(request,'prog/form_create_financial_report.html', context)
class ReportView(generic.ListView):
totalAmount = Expense.objects.aggregate(sum(expense_total))['totalAmount']
template_name = 'prog/report_status.html'
def get_queryset(self):
return Report.objects.all()
def report_edit(request, report_id):
report = Report.objects.get(id=report_id)
form = ReportForm(request.POST or None, instance=report)
object_list = Report.objects.all()
if form.is_valid():
report.save()
messages.success(request, ('the report has been updated'))
return redirect('prog:reports')
else:
context = {
'form': form,
'object_list': object_list
}
return render(request, 'prog/form_edit_report.html', context)
def delete_report(request, report_id):
report = get_object_or_404(Report,id=report_id)
form = ReportForm(request.POST or None, instance=report)
object_list = Report.objects.all()
if form.is_valid():
report.delete()
return redirect('prog:reports')
else:
context = {
'form': form,
'object_list': object_list
}
return render(request, 'prog/form_delete_report.html', context)
def report_detail(request, report_id):
report = get_object_or_404(Report,id=report_id)
return render(request, 'prog/report_detail.html',{'report':report})
def create_expense(request, report_id):
form = ExpenseForm(request.POST or None, request.FILES or None)
report = get_object_or_404(Report,pk=report_id)
if form.is_valid():
expense = form.save(commit=False)
expense.report =report
return render(request, 'prog/report_detail.html', {'report':report})
context ={
'report':report,
'form':form
}
return render(request, 'prog/form_create_expense.html', context)
我希望结果是属于报表对象的所有costum_total的总和。每当创建新费用时,其总费用应自动添加到report_toalAmount。
创建费用后,应该自动填充report.totalAmount
并传递到report_detail(Listview)中的模板
答案 0 :(得分:0)
您可以使用Django信号装饰器来“监听”数据库中的更改。
某些事情应该起作用:
@receiver(post_save, sender=Expense)
def update_report(sender, instance, created, **kwargs):
if created: #validate a new object was created and not updated
report = Report.objects.get() #use the primary key of your report
report.totalAmount += instance.total
report.save()
我们在信号装饰器中使用post_save
,这样该函数将仅在创建模型后执行。
instance
参数是已经创建的模型,我们可以使用它来检索所需的数据。我建议您阅读有关信号的信息,它们经常派上用场。
创建费用后,报表对象将立即更新。只需将其作为参数传递到report_detail视图,就应该一切就绪。
正如有人已经在评论部分中建议的那样,请查看Django Signals,以进一步阅读该主题。