3

我想知道是否有办法使用查找中的值对模型中的字段执行批量更新。

假设这个模型:

class Product(models.Model):
    price = models.DecimalField(... field params here ...)
    ... more fields here ...

class ShopcartProductEntry(models.Model):
    oncommit_price = models.DecimalField(
        ... field params here, similar to price params ...)
    quantity = models.IntegerField(... field params, doesn't matter here ...)
    product = models.ForeignKey(Product, null=False)
    shopcart = models.ForeignKey(
                   Shopcart, null=False, related_name='entries', ... more params ...)

class Shopcart(models.Model):
    ... fields here ...

    def commit(self):
        pass #my question will come in this method

正如医生所说,如果我写:

    def commit(self):
        self.entries.update(oncommit_price=F('product__price'))

姜戈会哭的。我该怎么做那个查询?目前我遍历每个条目。我不喜欢那样。

4

1 回答 1

2

作为最后的手段,您始终可以编写自己的 SQLUPDATE查询:

sql = ''' UPDATE myapp_shopcartproductentry SPE
          JOIN myapp_product P ON P.id = SPE.product_id
          SET SPE.oncommit_price = P.price
          WHERE SPE.shopcart_id = %s '''

然后使用自定义 SQL 事务直接执行它:

def commit(self):
    sql = ''' ... SQL as above ... '''
    from django.db import connection, transaction
    cursor = connection.cursor()
    cursor.execute(sql, [self.id])
    transaction.commit_unless_managed()
于 2013-04-08T14:52:35.037 回答