我可以使用 Django ORM 获得 PostgreSQL 查询的结果吗?

Can I get this result of PostgreSQL query using Django ORM?

我在使用 django ORM 时遇到了问题。 我想获取在视图中使用 PostgreSQLraw sql query 可以获得的数据。但是有什么解决方案可以使用 Django ORM 来实现这一点。 这是我的模型

class Invoice(models.Model):
    class PaymentMode(models.TextChoices):
        Cash = 0, _('CASH')
        Credit = 1, _('CREDIT')

    class PaymentStatus(models.TextChoices):
        Paid = 0, _('PAID')
        Pending = 1, _('PENDING')

    total_amount = models.IntegerField()
    payment_mode = models.CharField(choices=PaymentMode.choices,
                                    max_length=20,
                                    default=PaymentMode.Credit)
    payment_status = models.CharField(choices=PaymentStatus.choices,
                                      default=PaymentStatus.Pending,
                                      max_length=15)
    print_date = models.DateField(default=now)
    invoice_date = models.DateField(default=now)
    created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING)


class Payment(models.Model):
    class PaymentMethod(models.TextChoices):
        Cash = 0, _('CASH')
        Cheque = 1, _('CHEQUE')
        OnlineTransfer = 2, _('WEB_TRANSFER')
        Other = 3, _('OTHER')

    invoice = models.ForeignKey(Invoice,
                                on_delete=models.DO_NOTHING,
                                default=0)
    amount = models.IntegerField()
    date = models.DateField(default=now)
    recieved_by = models.CharField(max_length=150)
    payment_method = models.CharField(choices=PaymentMethod.choices,
                                      default=PaymentMethod.Cash,
                                      max_length=20)

这是我的 PostgreSQL 查询

SELECT 
    A.id ,
    A.total_amount ,
    A.payment_mode,
    A.payment_status,
    A.print_date,
    A.invoice_date,
    A.created_by_id,
    A.customer_id,
    coalesce(SUM(P.amount), 0) AS "paid",
    (A.total_amount - coalesce(SUM(P.amount), 0)) As "remaining"
    FROM
        public."Invoicing_invoice" as A
    LEFT JOIN public."Invoicing_payment" as P
        ON P.invoice_id = A.id   
    GROUP BY A.id

您可以使用以下方式进行注释:

from django.db.models import F, Sum, Value
from django.db.models.functions import Coalesce

Invoice.objects.annotate(
    paid=<b>Coalesce(Sum(payment__amount), Value(0))</b>,
    remaining=<b>F('total_amount') -</b> Coalesce(Sum(payment__amount), Value(0))
)

由此查询集产生的 Invoice 将有两个额外的属性 .paid.remaining 以及发票的已付金额和剩余金额。