代码之家  ›  专栏  ›  技术社区  ›  Samuel Dauzon

Django模型根据另一个字段更新计算字段

  •  0
  • Samuel Dauzon  · 技术社区  · 5 年前

    我使用Django,希望通过使用类似于SQL的计算来更新模型的许多记录:

    UPDATE table SET amount = pre_tax * 1.2 WHERE amount IS NULL;
    

    我想和詹戈·奥姆一起做。我没找到任何办法。

    这个答案 Django - Update model field based on another field 不要使用批量更新,我需要一个允许更新多个记录的语法。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Iain Shelvington    5 年前

    你可以用 F expression .update() to update multiple records at once . 这个 F型 表达式允许您引用行中的现有值

    Model.objects.filter(amount__isnull=True).update(amount=F('pre_tax') * 1.2)