queryset.update不起作用



我想更改任何数据库变量的名称,如果其匹配ABC。

def icall(modeladmin, request, queryset):
    for pri in queryset:
        print('from test:', pri.name, pri.title) # priting if working fine
        if pri.name == 'abc':        # loop is matching the condition
            pri.update(name='zzz')  ## the value is not getting update in DB
        else:                                      
            print("gg not mached")

pri.update(name='zzz') OS在这里不起作用。

有人可以帮助我知道正确的语句,以根据其他条件更新数据库。

def icall(modeladmin, request, queryset):
    for pri in queryset:
        print('from test:', pri.name, pri.title)
        if pri.name == 'abc':
            pri.name ='zzz'
            pri.save()
            print("working")
        else:
            print("gg not mached")

更新查询是在QuerySet上完成的。它不是像您想做的那样在单个对象上完成的。您可以简单地做

queryset.filter(name='abc').update(name='zzz')

您无法使用更新查询更新单个对象。可以使用更新在整个QuerySet中更新对象。请参考文档以获取澄清:Django更新查询

在您的情况下。您可以做:

queryset.filter(name='abc').update(name='zzz')

而不是前线。

for pri in queryset:
    if pri.name == 'abc':        # loop is matching the condition
        pri.name='zzz'
        pri.save() # save the updated value

这是如果您在模型上附有信号。更新查询实际上没有使用Django保存,因此不会发出pre_save,postrongave信号。

相关内容

最新更新