162 | | we want Restaurant to have a 'name' CharField. However, fields from parent classes are not included when the class is created. |
| 162 | we want Restaurant to have a 'name' CharField. Looking at our above example, it would seem that 'name' should automatically be inherited by Restaurant. However, this is not the case, as Django is using metaclasses to modify the default class creation behavior. 'Place' is not created strictly as defined above. The ModelBase metaclass instead creates a new class from scratch (see dm/models/base.py), and each of the field attributes are added to the class in such as way that they are not inherited by subclasses. Note how 'name' would not show up under a call to dir(Place). |
| 163 | |
| 164 | Each of the fields is added to the class via a call to add_to_class(). This in turn calls contribute_to_class in the case of field objects, rather than calling setattr(), which is why the fields of a parent class are not available to the child class for inheriting. In other words, by the time Restaurant is created, the definition of it's parent would change from this: |
| 165 | |
| 166 | {{{ |
| 167 | class Place(models.Model): |
| 168 | name = models.CharField(maxlength=50) |
| 169 | }}} |
| 170 | |
| 171 | to something more like this: |
| 172 | |
| 173 | {{{ |
| 174 | class Place(models.Model): |
| 175 | _meta = ... |
| 176 | }}} |