Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using self in Django Model classes

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.

like image 905
Kartik Rustagi Avatar asked Jun 29 '11 16:06

Kartik Rustagi


1 Answers

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:

  • https://code.djangoproject.com/wiki/DynamicModels
  • https://code.djangoproject.com/wiki/DevModelCreation
like image 99
Shawn Chin Avatar answered Nov 03 '22 23:11

Shawn Chin