0

Django 1.11.7 MySQL

I was trying to change the value of an object like this:

# change the value of the filed and save

def patch(...): 
   instance.field_name = new_name
   instance.save()
   print(instance.filed_name)

When I run the code I got the print result as new_name. But when I check the database manually I got the result as old_name.

Then I tried ways like:

instance.save(update_fields=['field'])

and

ModelName.objects.filter(id=instance.id).update(field_name=new_name)

but get the above problem as well. And meanwhile, the project runs perfectly functional except for this segment of code.

Any idea what caused this problem or suggestion on how to solve it?

唐思佳
  • 11
  • 1
  • 3

1 Answers1

0
  1. Is that piece of code inside a transaction? Maybe the transaction gets rolledback somewhere later.
  2. When you read from the DB are you inside a transaction? Some transaction modes may not show you this change.
  3. Are you sure that field_name is the correct field name? Maybe you have a typo and you just set a property of the object without changing model field. From what I see you sometimes type "field_name" and sometimes "filed_name"
Maciek
  • 3,174
  • 1
  • 22
  • 26
  • :( Sorry for the typo but I'm pretty sure that it's correct in the code. And no it's not inside a transaction. – 唐思佳 Sep 20 '18 at 11:44
  • @唐思佳 You can try turning on DB commands logging to see if the UPDATE is executed correctly: https://stackoverflow.com/questions/4375784/log-all-sql-queries – Maciek Sep 20 '18 at 12:15