Django模型如何工作? [英] How do Django models work?

查看:101
本文介绍了Django模型如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 从django.db导入模型

class Something(models.Model):
title = models.TextField(max_length = 200)

我可以这样工作:

  thing = Something()
#set title
thing.title =第一件事
#get title
thing.title

所有的作品都应该是这样的,但我想了解它是如何工作的。

  title = models.TextField(max_length = 200 )

在非Django中的Python代码行定义类型为model.TextField的类变量标题,我可以访问它也是这样的: thing .__ class __。title 链接



但是在Django中,当我创建某些东西的实例时,我突然有一个标题属性,我可以获取/设置文本。并且不能访问它与的东西.__类__。标题所以清楚当做thing.title我没有访问类变量标题,但一些生成的属性/属性,或? / p>

我知道这些字段最后在thing._meta.fields但是怎么样?



1,Django是否在幕后创建属性title?



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

解决方案

我觉得很难打败Django文档必须对此说


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


基本上是一个元类定义了如何创建一个类本身。在创建过程中,附加的属性/方法/任何东西都可以绑定到该类。 stackoverflow answer 的示例给出了大小写所有类的属性#这样的类,所以你可以从...继承
class UpperAttrMetaclass(type):
#__new__是__init__之前调用的方法
#它是创建对象并返回它的方法
#,而__init__只是初始化传递的对象作为参数
#你很少使用__new__,除非你想要控制如何创建对象
#。
#这里创建的对象是类,我们要自定义它
#所以我们覆盖__new__
#你可以在__init__中做一些东西,如果你想要
#一些高级使用也涉及覆盖__call__,但是我们不会
#看到这个
def __new __(upperattr_metaclass,future_class_name,
future_class_parents,future_class_attr):

attrs = (name,value)name,value在future_class_attr.items()中,如果不是name.startswith('__'))
uppercase_attr = dict((name.upper(),value) )

返回类型(future_class_name,future_class_parents,uppercase_attr)

方式,Django的元模型可以将您应用于类的属性进行消化,并为验证/ etc添加各种有用的属性,包括甚至方法和不需要的。


So I can create Django model like this:

from django.db import models

class Something(models.Model):
    title = models.TextField(max_length=200)

and I can work with it like this:

thing = Something()
#set title
thing.title = "First thing"
#get title
thing.title

All works as it should but I'd like to understand HOW it works.

title = models.TextField(max_length=200)

in non-Django Python code above line defines class variable title of type models.TextField and I could access it also like this: thing.__class__.title(link)

But in Django when I create instance of Something I suddenly have a title attribute where I can get/set text. And cannot access it with thing.__class__.title So clearly when doing thing.title I'm not accessing class variable "title" but some generated attribute/property, or?

I know that fields ended up in thing._meta.fields but how? What's going on and how?

1, Does Django create property "title" behind the scenes?

2, What happened to class variable "title"?

解决方案

I think its hard to beat what Django documentation has to 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.

Basically a metaclass defines how a class itself will be created. During creation, additional attributes/methods/anything can be bound to that class. The example this stackoverflow answer gives, capitalizes all the attributes of a class

# 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)

In a similar way, Django's metaclass for Models can digest the attributes you've applied to the class and add various useful attributes for validation/etc, including even methods and what-not.

这篇关于Django模型如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆