【问题标题】:How to multiply 2 columns in Django ORM如何在 Django ORM 中将 2 列相乘
【发布时间】:2020-12-13 21:10:27
【问题描述】:

我有一个记录发票行条目的 MySQL 表。我想将unit_pricequantity 相乘以获得sub_total(多行条目)。这是我的line_entries_table 的样子

invoice_id| unit_price| quantity    
    14646 | 521.2900  | 1.9000  
    14646 | 200.9900  | 1.5900  
    14646 | 260.0700  | 1.5800  
    14646 | 375.1700  | 1.7100  
    14646 | 496.4300  | 1.8800  
    14646 | 164.3100  | 1.6100  
    14646 | 279.2200  | 1.6400  
    14646 | 343.0100  | 1.7200  
    --------------------------
    25728 | 326.3400  | 1.5300  
    25728 | 521.2900  | 1.9000  
    25728 | 200.9900  | 1.5900  
    25728 | 260.0700  | 1.5800  
    25728 | 375.1700  | 1.7100  
    25728 | 496.4300  | 1.8800  
    25728 | 164.3100  | 1.6100  
    25728 | 279.2200  | 1.6400  
    25728 | 343.0100  | 1.7200  
    25728 | 326.3400  | 1.5300  

结果:

invoice_id| sub_total
14646   |   5107.5021
25728   |   2698.8797

我想一次获取所有发票的 sub_total。这是适用于我的 MySQL 命令:

select invoice_id,  SUM(unit_price*quantity) AS sub_total from details_invoice_service_details WHERE invoice_id IN (14646 ,25728) GROUP BY invoice_id

知道如何在 Django 中实现这一点:

这里是部分代码,我试过了:

rows = invoice.models.InvoiceLineEntries_Model.objects.filter(invoice_id__in=invoice_ids)

【问题讨论】:

  • F() expressions 应该能帮到你
  • 使用注解 Sum 和 F 表达式
  • 你能帮我举个例子吗?

标签: python django django-models django-queryset django-orm


【解决方案1】:

我假设你有一个模型如下,

class InvoiceLineEntries(models.Model):
    invoice_id = models.IntegerField()
    unit_price = models.FloatField()
    quantity = models.FloatField()

然后,使用F(...) 表达式为,

from django.db.models import F

InvoiceLineEntries.objects.annotate(sub_total=F('unit_price') * F('quantity'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-28
    • 2013-08-15
    • 1970-01-01
    • 2022-09-26
    • 2020-11-29
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    相关资源
    最近更新 更多