在 django 中进行查询并 return 我所有对象的总和
Making a query in django and return sum of all my objects
我有这个型号
class Invoice(models.Model):
field1= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
amount_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
price_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
我可以有几张发票,所以我想对所有发票进行 (amount_field2*price_field2) 和 SUM,最后得到总计。在我看来,我需要这样做,因为我等待 return 我的模板总数。
已经找到解决方案:
query = Invoice.objects.aggregate(total= Sum(F('amout_field2') * F('price_field2')),)
class Invoice(models.Model):
field1= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
amount_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
price_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
def single_invoice_total(self):
return self.amount_field2 * self.price_field2
def get_total_of_all_invoices(self):
total = 0
for single_invoice in self.Invoice.all():
total += single_invoice.single_invoice_total()
return total
并且您可以通过视图上下文发送来在您的模板中显示它
您可以通过
访问总数
{{ Invoice.get_total_of_all_invoices }}
我有这个型号
class Invoice(models.Model):
field1= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
amount_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
price_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
我可以有几张发票,所以我想对所有发票进行 (amount_field2*price_field2) 和 SUM,最后得到总计。在我看来,我需要这样做,因为我等待 return 我的模板总数。
已经找到解决方案:
query = Invoice.objects.aggregate(total= Sum(F('amout_field2') * F('price_field2')),)
class Invoice(models.Model):
field1= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
amount_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
price_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
def single_invoice_total(self):
return self.amount_field2 * self.price_field2
def get_total_of_all_invoices(self):
total = 0
for single_invoice in self.Invoice.all():
total += single_invoice.single_invoice_total()
return total
并且您可以通过视图上下文发送来在您的模板中显示它
您可以通过
访问总数
{{ Invoice.get_total_of_all_invoices }}