1

I want to change the name for any database variable if its match 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")

the pri.update(name='zzz') os not working here.

can someone please help me to know the correct statement to update the database based on the if else condition.

Sandeep Balagopal
  • 1,943
  • 18
  • 28
  • Please look into this https://docs.djangoproject.com/en/1.11/ref/models/conditional-expressions/#conditional-update – itzMEonTV Dec 06 '17 at 08:52

3 Answers3

2
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")
aprasanth
  • 1,079
  • 7
  • 20
1

Update query is done on a queryset. It is not done on a single object like you are trying to do. You can simply do

queryset.filter(name='abc').update(name='zzz')
Sandeep Balagopal
  • 1,943
  • 18
  • 28
0

You cannot update a single object using the update query. Can update objects in a queryset as a whole using update. Please refer the document for clarification: Django Update query

In your case. You can do:

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

instead of the for-loop.

OR

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

This is in case you have signals attached to your models. The Update query does not actually use django save and consequently does not emit pre_save, post_save signals.

rajkris
  • 1,775
  • 1
  • 9
  • 16