Does django (python) reuse object? -


suppose have model field field1

class myclass(models.model):     field1 = models.charfield(max_length=100) 

somewhere have code like

my_object = myclass()  my_object.field1 = 'a' my_object.another_field = 'b' # (it's not defined in model class) 

is there chance another_object = myclass() have another_field set?

no, another_field unique instance assigned to. particular python, irrespective of django. try in python console:

>>> class myclass(): >>>   field1 = "field 1" >>> x = myclass() >>> x.another_field = "another field!" >>> x.field1 'field 1' >>> x.another_field 'another field!' >>> y = myclass() >>> y.field1 'field 1' >>> y.another_field traceback (most recent call last): file "<stdin>", line 1, in <module> attributeerror: myclass instance has no attribute 'another_field' 

if want add new field class dynamically, can adding directly class (as opposed instance) follows:

>>> myclass.newer_field = "this newest field"  

now, can see newer field available, existing objects:

>>> x.newer_field 'this newest field' >>> y.newer_field 'this newest field' 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -