While adding model class to models.py in Django, why don't we use self with the field variables which we define? Shouldn't not using self field variables make them class variables instead,which "may" cause a problem.
Asked
Active
Viewed 1.1k times
13
-
... what? Can you add a couple examples of what you mean? Because I'm not sure I'm following you... – eternicode Jun 29 '11 at 17:14
1 Answers
12
Django uses metaclasses to create the actual class based on the class definition your provide. In brief, upon instantiation of your model class, the metaclass will run through your model field definitions and return a corresponding class with the appropriate attributes.
To answer your question directly, using class variables instead of instance variables (object.self
) allows the metaclass to inspect the class attributes without having to first instantiate it.
For more information, have a look at the source and the following docs:

Shawn Chin
- 84,080
- 19
- 162
- 191
-
3I asked a similar question of myself about 4 years ago, so I dove into the `django/db` code. It was enlightening on several levels; it's sort of a Masters Class in metaclass usage. – Peter Rowell Jun 29 '11 at 18:20