模型.py:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
在 Python 中调用dir
类上的函数通常会显示一个列表,其中包含已定义的类变量。但奇怪的是,当我执行python manage.py shell
以下操作时:
>>> 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)
不包含title
andbody
类变量(意外)。dir(bm.Blog())
但是确实包含那些类变量(预期的)。
>>> 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']
Model
那么为什么当我在该类上调用 dir 函数时,我看不到 Django 子类的类变量呢?