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.
- [Answered ]-Django 1.10 error, 'NoneType' object is not callable
- [Answered ]-UpdateView form pre-populate error
- [Answered ]-Django Using Annotate Instead of Distinct()
- [Answered ]-Django get model with foreign key