使用分组在Django中进行有条件的批量更新

时间:2019-02-11 08:17:07

标签: sql django postgresql django-models django-orm

假设我有一个具有以下模型定义的交易清单:

class Transaction(models.Model):
    amount = models.FloatField()
    client = models.ForeignKey(Client)
    date = models.DateField()
    description = models.CharField()
    invoice = models.ForeignKey(Invoice, null=True)

现在,我想在月底为每个客户创建发票。发票模型如下:

class Invoice(models.Model):
    client = models.ForeignKey(Client)
    invoice_date = models.DateField()
    invoice_number = models.CharField(unique=True)

    def amount_due(self):
        return self.transaction_set.aggregate(Sum('amount'))

def create_invoices(invoice_date):
    for client in Client.objects.all():
    transactions = Transaction.objects.filter(client=client)
    if transactions.exists():
        invoice = Invoice(client=client, number=get_invoice_number(), date=invoice_date)
            invoice.save()
            transactions.update(invoice=invoice)

我知道我可以使用批量创建在1个查询中使用批量创建来创建所有发票,但是我仍然必须分别在交易模型中设置发票字段。

创建所有发票后,是否可以通过单个查询设置所有交易模型的发票字段?最好是在使用ORM时,但愿意时使用原始SQL。

我知道我也可以使用交易列表上的按客户分组以获取每个客户的总额,但是各个条目不会链接到发票。

2 个答案:

答案 0 :(得分:5)

补充@Bernhard Vallant的答案。您只能使用3个查询。

def create_invoices(invoice_date):
    # Maybe use Exists clause here instead of subquery, 
    # do some tests for your case if the query is slow
    clients_with_transactions = Client.objects.filter(
        id__in=Transaction.objects.values('client')
    )

    invoices = [
        Invoice(client=client, number=get_invoice_number(), date=invoice_date)
        for client in clients_with_transactions
    ]

    # With PostgreSQL Django can populate id's here
    invoices = Invoice.objects.bulk_create(invoices)

    # And now use a conditional update
    cases = [
        When(client_id=invoice.client_id, then=Value(invoice.pk))
        for invoice in invoices
    ]
    Transaction.objects.update(invoice_id=Case(*cases))

答案 1 :(得分:4)

如果能够在以下之前生成从客户到发票的映射,则可以尝试构建conditional update query

from django.db.models import Case, Value, When

# generate this after creating the invoices
client_invoice_mapping = {
    # client: invoice
}

cases = [When(client_id=client.pk, then=Value(invoice.pk)) 
         for client, invoice in client_invoice_mapping.items()]

Transaction.objects.update(invoice_id=Case(*cases))

请注意,条件查询自Django 1.8起可用。否则,您可能会考虑使用原始SQL构建类似的东西。