fluffy_muffin fluffy_muffin - 4 months ago 23
Python Question

how do djangos field instances work in models

Something I'm confused about in Django is how the model's fields work.

You define them as class variables.

So, a class like this:

class Foo:
avar = "something here"


And if you created two instances.

f1 = Foo()
f2 = Foo()


And you set avar to be something else, this would affect both instances of
Foo
. So, how does django keep the models field values between instances correct? Does it simply use the base class variables to create the tables, and then query the database for the model / table to return the correct field values for respective instances?

Or, does it do something at the metaclass level to defer creation, until say the models
__init__
/
__new__
and then create unique instances of the fields?

Going further... for something like
amodel = AModel.objects.get(*)
I could see how Django would hit the database and then perhaps return an instance of the model class with the column values filled in for the fields so you could access the attribute
amodel.field
for the value correctly. This would make sense, but I'm not sure I understand how the internals of this work.

Answer

A regular class variable is a property of the class. It is not stored in the database (only model fields are). In your case, avar is not a model field. It is just a simple python class variable.

If you change the class variable on an instance of Foo, it will only affect that instance. All other instances will not be affected. Proof:

class Foo:
    avar = 'Something'

a = Foo()
b = Foo()

a.avar = 'Something else'

print a.avar
> 'Something else'

print b.avar
> 'Something'

Note that changing avar on a does not alter it on b. Note also that the changed value of a.avar will only exist as long as a itself exists. This property is not stored in the database and if you load a new object from the database it will just have the default avar of the class.

Comments