Django queryset.update在for循环中不起作用
我想更改任何数据库变量的名称,如果它与abc匹配Django queryset.update在for循环中不起作用,django,django-admin-actions,Django,Django Admin Actions,我想更改任何数据库变量的名称,如果它与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 p
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在此不工作
有人能帮我知道根据if-else条件更新数据库的正确语句吗。更新查询是在查询集上完成的。它不是像您尝试的那样在单个对象上完成的。你可以简单地做
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.filter(name='abc').update(name='zzz')
不能使用更新查询更新单个对象。可以使用update作为一个整体更新queryset中的对象。请参考文件进行澄清: 就你而言。你可以做:
queryset.filter(name='abc').update(name='zzz')
而不是for循环
或
这是为了防止您的模型连接了信号。更新查询实际上不使用django save,因此不会发出保存前、保存后信号。我认为您不需要queryset.objects.filter,只需queryset.filter就足够了。是否有任何方法在if条件下匹配queryset.filter(name='abc')?if queryset.filter(name='abc')):然后:如果queryset.filter(name='def'):然后:执行“dosomething”…是否更新字段?是的,您可以这样做。如果re.match(regex,content)不是None:blah。。明白了:)请调查一下
for pri in queryset:
if pri.name == 'abc': # loop is matching the condition
pri.name='zzz'
pri.save() # save the updated value