models.py:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
Calling the dir function on a class in Python normally shows a list that includes class variables if they are defined. But strangely when I do python manage.py shell and do the following:
>>> import blog.models as bm
>>> dir(bm.Blog)
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__',
'__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__',
'__metaclass__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__',
'__weakref__', '_base_manager', '_default_manager', '_deferred', '_get_FIELD_display',
'_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val',
'_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks',
'_set_pk_val', 'clean', 'clean_fields', 'date_error_message', 'delete', 'full_clean',
'objects', 'pk', 'prepare_database_save', 'save', 'save_base', 'serializable_value',
'unique_error_message', 'validate_unique']
dir(bm.Blog) does not contain the title and body class variables (unexpected). dir(bm.Blog()) however does contain those class variables (expected).
>>> dir(bm.Blog())
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__',
'__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__',
'__metaclass__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__',
'__weakref__', '_base_manager', '_default_manager', '_deferred', '_get_FIELD_display',
'_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val',
'_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks',
'_set_pk_val', '_state', 'body', 'clean', 'clean_fields', 'date_error_message',
'delete', 'full_clean', 'id', 'objects', 'pk', 'prepare_database_save', 'save',
'save_base', 'serializable_value', 'title', 'unique_error_message', 'validate_unique']
So why can’t I see the class variables of a Django Model subclass when I call the dir function on that class?
This happens because you have inherited from
db.Model, which has a specific metaclassModelBase. Sotitle=models.CharFieldand other fields (that provides meta information about rows in your table) are not real attributes of the model-class, instead of values of this fields in model-instance. But you can get access to them: