[Answered ]-Django's Model fields are defined on the class level?

2👍

✅

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.

0👍

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

Leave a comment