1
# Model contains only one JSON field
class TestModel(models.Model):
    field = JSONField(default=dict)

# Dictionary, assigned to model.field
field_json = {"test": 5}
model = TestModel(field = field_json)
model.save() 

# Returns true. WHY???
print(id(model.field) == id(field_json))

After saving a model, shouldn't the model refresh from db? Why is the model field retaining a mutable reference to the original dictionary object?

1 Answers1

0

After saving a model, shouldn't the model refresh from db?

No, it is not refreshed. It simply makes an CREATE or INSERT INTO statement at the database. So here it will look like:

INSERT INTO appname_test_model (field) VALUES ('{"test": 5}');

That is all, the object remains the same. In fact if you for example have a DecimalField and you assign it an int, it will still remain an int.

If the primary key is an AutoField (or a BigAutoField), it will also set the primary key of the object the first time it saves that object:

As specified in Saving objects section of the documentation:

To save an object back to the database, call save().

(…)

The model save process also has some subtleties; see the sections below.

Auto-incrementing primary keys

If a model has an AutoField — an auto-incrementing primary key — then that auto-incremented value will be calculated and saved as an attribute on your object the first time you call save().

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thank you Willem. However, for example a model which does not have a pk, after saving has a pk assigned. Isn't this id coming from the DB? So in that case, the object is actually not the same right? – Neil Sanghrajka Jun 10 '20 at 18:39
  • @NeilSanghrajka: yes, it will indeed select the latest assigned primary key, but that is the only thing that returns from the database. – Willem Van Onsem Jun 10 '20 at 18:40
  • Thanks! I am trying to find Django documentation which explains this behaviour. If you can point me to some documentation, that would be awesome! Again thank you so much!! – Neil Sanghrajka Jun 10 '20 at 18:42