所以我可以像这样创建Django模型:
from django.db import models
class Something(models.Model):
title = models.TextField(max_length=200)
我可以像这样使用它:
thing = Something()
#set title
thing.title = "First thing"
#get title
thing.title
一切都应该正常工作,但我想了解它是如何工作的。
title = models.TextField(max_length=200)
在非Django Python代码中,上面一行定义了models.TextField类型的类变量title,我也可以像这样访问它:thing.__class__.title
(link)
但是在Django中,当我创建一些东西的实例时,我突然有了一个title属性,我可以在其中获取/设置文本。在执行thing.title时,我不是在访问类变量"title“,而是访问一些生成的属性/属性,所以无法用thing.__class__.title
清楚地访问它,或者?
我知道字段在thing._meta.fields中结束了,但是如何结束呢?发生了什么,是如何发生的?
1、Django是否在幕后创建了属性"title“?
2,类变量"title“发生了什么?
发布于 2012-08-17 21:24:02
我认为很难超越Django文档对say on this的影响。
模型类(参见base.py)有一个元类属性,该属性将ModelBase (也在base.py中)定义为用于创建新类的类。因此,调用ModelBase.新的来创建这个新的示例类。重要的是要认识到,我们在这里创建的是类对象,而不是它的实例。换句话说,Python创建的东西最终将绑定到当前名称空间中的示例名称。
基本上,metaclass定义了如何创建类本身。在创建过程中,可以将其他属性/方法/任何内容绑定到该类。此stackoverflow answer给出的示例将一个类的所有属性大写
# 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)
以类似的方式,Django的模型元类可以消化您应用于类的属性,并为验证/等添加各种有用的属性,甚至包括方法和其他。
发布于 2012-08-17 21:49:38
python的功能非常强大,允许开发人员使用入侵。
django使用了很多元类。看起来models.Model也在使用它。请参阅django\db\models\base.py中的
class Model(object):
__metaclass__ = ModelBase
我认为元类只需要获取类的属性,比如字段,并且对于这些Model子类的所有新实例,创建适当的变量。
1)是的,django自动创建属性"title“的实例变量2)以同样的方式,元类将字段移动到元类中……
https://stackoverflow.com/questions/12006267
复制相似问题