Reputation: 4353
I don't know if this is a bug or Django just allows it to happen. I have a Django model:
class Author(models.Model):
name = models.CharField(max_length=128)
I create an instance of it and assign a value to a non-existent field address
:
author = Author()
author.name = 'abce'
author.address = 'defg'
author.save()
The instance is saved successfully and there is no error messages. Is this normal?
Upvotes: 0
Views: 226
Reputation: 20349
Yeah Normal. Django will do update only for the field you defined
From django code
for field in self._meta.concrete_fields: if field.attname in non_loaded_fields: # This field wasn't refreshed - skip ahead. continue setattr(self, field.attname, getattr(db_instance, field.attname))
You can see fields by
Author()._meta.concrete_fields
But you cannot do this like
Author(name="name", address="sss")
It will raise invalid argument.
Upvotes: 1
Reputation: 19806
In Python, user-defined types are generally mutable
, which means they can be altered, and adding an attribute
to a user-defined object
is just like adding a key
to an ordinary dictionary
. You can check this answer for more details are user defined classes mutable
Upvotes: 1
Reputation: 43300
Yes its normal, The address never actually gets saved and if you were to reference this object again, it wouldn't be there. Its just that Python qwerk that you are allowed to add fields to an object instance whenever you want
class A:
pass
a = A()
a.foo = 1
Whether or not you should is a different matter...
Upvotes: 1