Django模型如何工作?

Mic*_*hal 20 python django django-models

所以我可以像这样创建Django模型:

from django.db import models

class Something(models.Model):
    title = models.TextField(max_length=200)
Run Code Online (Sandbox Code Playgroud)

我可以像这样工作:

thing = Something()
#set title
thing.title = "First thing"
#get title
thing.title
Run Code Online (Sandbox Code Playgroud)

一切正常,但我想了解它是如何工作的.

title = models.TextField(max_length=200)
Run Code Online (Sandbox Code Playgroud)

在非Django的Python的上面的行的代码定义类型models.TextField的类变量标题和我也可以访问它是这样的:thing.__class__.title(链接)

但是在Django中,当我创建Something的实例时,我突然有一个title属性,我可以在其中获取/设置文本.并且无法thing.__class__.title在执行thing时明确地访问它.标题我没有访问类变量"title"但是有些生成了属性/属性,或者?

我知道那些字段最终出现在thing._meta.fields但是怎么样?发生了什么事,怎么了?

1,Django幕后创建属性"头衔"吗?

2,类变量"title"发生了什么变化?

Dou*_* T. 17

我认为很难击败Django文档对此的看法.

Model类(参见base.py)有一个元类属性,它定义ModelBase(也在base.py中)作为用于创建新类的类.所以ModelBase.调用new来创建这个新的Example类.重要的是要意识到我们在这里创建了类对象,而不是它的实例.换句话说,Python正在创建最终将绑定到当前名称空间中的Example名称的东西.

基本上,元类定义了如何创建类本身.在创建过程中,可以将其他属性/方法/任何内容绑定到该类.此stackoverflow回答给出的示例,大写了类的所有属性

# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type): 
    # __new__ is the method called before __init__
    # it's the method that creates the object and returns it
    # while __init__ just initializes the object passed as parameter
    # you rarely use __new__, except when you want to control how the object
    # is created.
    # here the created object is the class, and we want to customize it
    # so we override __new__
    # you can do some stuff in __init__ too if you wish
    # some advanced use involves overriding __call__ as well, but we won't
    # see this
    def __new__(upperattr_metaclass, future_class_name, 
                future_class_parents, future_class_attr):

        attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)

        return type(future_class_name, future_class_parents, uppercase_attr)
Run Code Online (Sandbox Code Playgroud)

以类似的方式,Django的模型元类可以消化您应用于类的属性,并为验证/等添加各种有用的属性,包括甚至方法和什么不是.