views:

28

answers:

2

Maybe my question is little childish. A django model is typically defined like this:

class DummyModel(models.Model):
    field1 = models.CharField()
    field2 = models.CharField()

As per my understanding, field1 and field2 are defined on the class level instead of instance level. So different instances will share the same field value. How can this be possible considering a web application should be thread safe? Am I missing something in my python learning curve?

+2  A: 

You are correct that normally attributes declared at the class level will be shared between instances. However, Django uses some clever code involving metaclasses to allow each instance to have different values. If you're interested in how this is possible, Marty Alchin's book Pro Django has a good explanation - or you could just read the code.

Daniel Roseman
A: 

Think of the models you define as specifications. You specify the fields that you want, and when Django hands you back an instance, it has used your specifications to build you an entirely different object that looks the same.

For instance,

field1 = models.CharField()

When you assign a value to field1, such as 'I am a field', don't you think it's strange that you can assign a string to a field that is supposed to be a 'CharField'? But when you save that instance, everything still works?

Django looks at the CharField, says "this should be a string", and hands it off to you. When you save it, Django checks the value against the specification you've given, and saves it if it's valid.

This is a very simplistic view of course, but it should highlight the difference between defining a model, and the actual instance you get to work with.

Josh Smeaton
Thanks, you explanation makes sense. I guess it's just more difficult to implement than simply giving an idea. With my knowledge, I don't know how to do this. Thanks for brilliant people (the Django team) who save us a lot of time.
Georgie Porgie
Wholeheartedly agree. Django and all its supporting utilities are brilliant pieces of work which make it a pleasure to use.
Josh Smeaton