【问题标题】:Django pass a list of values in update queryDjango 在更新查询中传递值列表
【发布时间】:2021-06-10 09:57:13
【问题描述】:

我有一个这样的 Django 查询:

object = BPMap.objects.filter(name = 'ABC', color = 'RED').values('quantity')

假设上述查询返回的输出是<QuerySet [100, 200, 300]>

现在我想在上述查询集上使用更新,但传递不同的值列表,例如

[150, 250, 350]

我想要一个类似于以下的查询:

BPMap.objects.filter(name = 'ABC', color = 'RED').update('quantity', [150, 250, 350])

我知道上面的查询是错误的。请指导我如何做到这一点。提前致谢。对不起,如果它微不足道,我是 Django 新手。

【问题讨论】:

  • 请分享模型。

标签: django django-models django-queryset


【解决方案1】:

update 不支持此功能,从您的示例来看,您只想在quantity 上添加 50。所以你可以这样做:

bpmaps = BPMap.objects.filter(name = 'ABC', color = 'RED')
for bpmap in bpmaps:
    bpmap.quantity += 50
    # or some other way you want to update

BPMap.objects.bulk_update(bpmaps, ['quantity'])

或者你可以使用F 表达式:

BPMap.objects.filter(name = 'ABC', color = 'RED').update(quantity=F('quantity') + 50)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多