如何使用Django ORM查询以计算数量乘以价格

时间:2019-04-03 02:02:37

标签: django model aggregate django-queryset

我想知道如何在Django ORM中获得总价格:数量乘以价格,以及模板使用哪个变量查看价值?

帖子已成功提交,但无法获得总价:这是我在views.py中拥有的内容:     上下文= {     “门票”:Ticket.objects.all(),

“总计”:Ticket.objects.filter(purchaser = User.objects.get(id = request.session ['user_id']))。aggregate(total_cost = Sum(F('price')* F('数量'),output_field = FloatField())     }     返回渲染(请求,“ first_app / confirmation.html”,上下文)

这是在我的models.py中:

from django.db import models
from django.db.models import Sum, Aggregate, F

class User(models.Model):
first_name=models.CharField(max_length=100)
last_name=models.CharField(max_length=100)
email=models.CharField(max_length=100)
password=models.CharField(max_length=100)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)

class Ticket(models.Model):
venue=models.CharField(max_length=100)
quantity=models.PositiveIntegerField(default=1)
price=models.DecimalField(default=25.00, max_digits=10, decimal_places=2, 
null=True, blank=True)
loop=models.CharField(max_length=100)
purchaser = models.ForeignKey(User, related_name="purchases", 
on_delete=models.PROTECT)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)

如何查询ORM以获取总数量*价格?在上下文中执行“票证”键之前还是之后,应该包含该查询?是否应在票证型号字段中添加该查询?如模型中所示,每个每个都被硬编码为25.00美元。谢谢,我将不胜感激!

1 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点。

1)您可以使用.annotate()

from django.db.models import F

tickets = Ticket.objects.all().annotate(total_price=F('total_quantity') * F('price'))

for t in tickets:
    print(t.total_price)

2)或者,您可以使用模型方法进行计算:

...
def total_price(self):
    return self.total_quantity * self.price

print(Ticket.objects.all()[0].total_price)

======================================

如果遵循方法1,则可以通过上下文访问此方法:

视图

...
tickets = Ticket.objects.all().annotate(total_price=F('total_quantity') * F('price'))
return render(request, 'template.html', {"tickets": tickets}

模板

{% for ticket in tickets %}
    ticket.total_price
{% endfor %}

如果您按照方法#2

视图

...
tickets = Ticket.objects.all()
return render(request, 'template.html', {"tickets": tickets}

模板

{% for ticket in tickets %}
    ticket.total_price
{% endfor %}