1

Going a bit crazy with something that stopped working in my Django app (Django 3.2.5, Python 3.9.6) - here's a simplified version:

class MyModel(models.Model):
  attribute_1 = models.CharField(max_length=1, default='0')

myModel = MyModel()
myModel.save()
print(myModel.attribute_1) # OUTPUTS '0'


myModel.attribute_1 = '1' # EDITED MY TYPO HERE...
myModel.save()
print(myModel.attribute_1) # OUTPUTS '1'

The second save() is not being saved, if I retrieve myModel from the database elsewhere I get attribute_1 equal to 0.

This, however, does work as I expect it to:

myModel = MyModel()
myModel.save()
MyModel.filter(pk=myModel.pk).update(attribute_1='1')

Am I missing something incredibly obvious here?

2
  • if you have a master-slave configuration then you might be reading from the slave and writing to the master. Commented Jul 14, 2021 at 3:58
  • @VishalSingh thanks but no it is not a master/slave. There is a cache, however, flushing the cache still does not result in the save taking place.
    – tunecrew
    Commented Jul 14, 2021 at 15:45

1 Answer 1

3

To set the attribute of your model instance you need to assign a new value to the attribute (field) you want to change;

# instead of
myModel(attribute_1='1')

# you'd do
myModel.attribute_1 = '1'
myModel.save()

# You could also use a more efficient save
myModel.save(update_fields=['attribute_1'])

If you're modifying objects like this you might also need to get the latest version from the database using refresh_from_db()

myModel.refresh_from_db()
4
  • Thanks - sorry that is my type in the code.
    – tunecrew
    Commented Jul 14, 2021 at 3:50
  • Fixed - the update_fields doesn't change the behaviour - will try the refresh_from_db() but why would that be necessary?
    – tunecrew
    Commented Jul 14, 2021 at 3:52
  • @tunecrew it's not necessary, but good to learn about these things Commented Jul 14, 2021 at 7:03
  • thanks @markwalker_ but the original question remains - it should save again as expected.
    – tunecrew
    Commented Jul 14, 2021 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.