gpt4 book ai didi

python - Django 模型是如何工作的?

转载 作者:IT老高 更新时间:2023-10-28 20:48:00 28 4
gpt4 key购买 nike

所以我可以像这样创建 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 类型的类变量标题,我也可以像这样访问它:thing.__class__.title(link)

但是在 Django 中,当我创建Something 的实例时,我突然有了一个标题属性,我可以在其中获取/设置文本。并且无法使用 thing.__class__.title 访问它所以很明显,在做 thing.title 时我不是在访问类变量“title”而是一些生成的属性/属性,或者?

我知道字段以 thing._meta.fields 结尾,但如何? 发生了什么以及如何?

1、Django是否在幕后创建属性“title”?

2、类变量“title”发生了什么?

最佳答案

我认为 Django 文档的内容很难超越 say on this .

The Model class (see base.py) has a metaclass attribute that defines ModelBase (also in base.py) as the class to use for creating new classes. So ModelBase.new is called to create this new Example class. It is important to realise that we are creating the class object here, not an instance of it. In other words, Python is creating the thing that will eventually be bound to the Example name in our current namespace.

基本上是 metaclass定义如何创建一个类本身。在创建期间,可以将其他属性/方法/任何东西绑定(bind)到该类。这个例子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 的模型元类可以消化您已应用于该类的属性,并添加各种有用的属性以进行验证/等,包括偶数方法和其他什么。

关于python - Django 模型是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12006267/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com