【问题标题】:Django : Update fields from lookup in a single .update() callDjango:在单个 .update() 调用中从查找更新字段
【发布时间】:2013-04-08 13:27:35
【问题描述】:

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

假设这个模型:

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 field lookup


    【解决方案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()
    

    【讨论】:

    • 谢谢。 stackoverflow 从来没有通知我这个答案。迟到总比没有好:p。收藏此页...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2014-01-09
    • 2019-10-08
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多