1

如果它与 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')这里不起作用。

有人可以帮助我了解根据 if else 条件更新数据库的正确语句。

4

3 回答 3

1
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")
于 2017-12-06T06:33:49.690 回答
1

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

queryset.filter(name='abc').update(name='zzz')
于 2017-12-06T06:34:09.223 回答
0

您不能使用更新查询更新单个对象。可以使用 update 整体更新查询集中的对象。请参阅文档进行说明:Django Update query

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

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

而不是 for 循环。

或者

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

这是在您的模型上附加了信号的情况下。Update 查询实际上并不使用 django save,因此不会发出 pre_save、post_save 信号。

于 2017-12-06T06:36:04.247 回答