Django:在单个.update()调用中更新查找字段

时间:2013-04-08 13:27:36

标签: django field lookup

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

假设这个模型:

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'))

Django会哭。我该怎么做那个查询?目前我迭代每个条目。我不喜欢那样。

1 个答案:

答案 0 :(得分:1)

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

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 '''

然后使用custom SQL transaction直接执行:

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()