Python 模型课是如何运作的,Django?

Python 模型课是如何运作的,Django?,python,django,inheritance,Python,Django,Inheritance,在发布这个问题之前,我已经阅读了Django官方文档,为初学者提供了全面的解释。我已经阅读了实际模型类的代码,并搜索了StackOverflow 在Django中使用数据库时,可以使用从models模块中的Model类继承的类。这有助于程序员避免重复键入所有内容,避免在特定于数据库的语法和python之间跳跃。正如我所读到的,“每个模型继承自的模型类自动负责翻译” 这是怎么回事?模型类如何将模型属性转换为数据库列?我假设从父模型类继承的一些方法能够使用每个新模型中指定的变量,但是如果可能的话,希

在发布这个问题之前,我已经阅读了Django官方文档,为初学者提供了全面的解释。我已经阅读了实际模型类的代码,并搜索了StackOverflow

在Django中使用数据库时,可以使用从models模块中的Model类继承的类。这有助于程序员避免重复键入所有内容,避免在特定于数据库的语法和python之间跳跃。正如我所读到的,“每个模型继承自的模型类自动负责翻译”

这是怎么回事?模型类如何将模型属性转换为数据库列?我假设从父模型类继承的一些方法能够使用每个新模型中指定的变量,但是如果可能的话,希望得到更好的解释

另外,如果模型类在models.base中,为什么要编写“models.Model”

链接到模型类:

编辑:


找出了模型的原因,模型起作用了

创建模型类并运行

python manage.py makemigrations

它创建相应的脚本以在数据库中创建表。 您可以在应用程序“迁移”文件夹中找到此脚本

当你跑的时候

python manage.py迁移


这些脚本映射到正确的命令,并由Django在数据库上执行。

当您创建模型类并运行

python manage.py makemigrations

它创建相应的脚本以在数据库中创建表。 您可以在应用程序“迁移”文件夹中找到此脚本

当你跑的时候

python manage.py迁移

这些脚本映射到正确的命令,并由Django在数据库上执行

模型类如何将模型属性转换为数据库列

模型
类本身并不真正进行任何转换。您创建了一个
Model
的子类,其中包含一些列信息, Django的ORM在构建与Django ORM查询相对应的数据库查询时使用的。转换是由数据库驱动程序在实际与特定数据库通信时完成的

这是一个行为有点像Django的
模型的玩具ORM
。如果您愿意,您可以实施
QuerySet
以获得乐趣:

class Column:
    '''
    Represents a database column.

    This is used to create the underlying table in the database
    and to translate database types to Python types.
    '''

    def __init__(self, type):
        self.type = type


class Manager:
    '''
    Accessed via `YourModel.objects`. This is what constructs
    a `QuerySet` object in Django.
    '''

    def __init__(self, model):
        self.model = model

    def get(self, id):
        '''
        Pretend `YourModel.objects.get(id=123)` queries the database directly.
        '''

        # Create an instance of the model. We only keep track of the model class.
        instance = self.model()

        # Populate the instance's attributes with the result of the database query
        for name in self.model._columns:
            # Pretend we load the values from the database
            value = 123
            setattr(instance, name, value)

        # This would be done above if we actually queried the database
        instance.id = id

        # Finally return the instance of `self.model`
        return instance


class ModelBase(type):
    def __new__(cls, name, bases, attrs):
        new_cls = super().__new__(cls, name, bases, attrs)

        # The `Manager` instance is made a class attribute
        new_cls.objects = Manager(new_cls)

        # Keep track of the columns for conveniece
        new_cls._columns = {}

        for name, attr in attrs.items():
            if isinstance(attr, Column):
                new_cls._columns[name] = attr

        # The class is now ready
        return new_cls


class Model(metaclass=ModelBase):
    '''
    Django's `Model` is more complex.
    This one only uses `ModelBase` as its metaclass so you can just inherit from it
    '''
    pass


class MyModel(Model):
    id = Column(int)
    column2 = Column(float)
    column3 = Column(str)


if __name__ == '__main__':
    print(MyModel._columns)

    instance = MyModel.objects.get(id=5)
    print(instance.id)
主要功能由
Model
作为元类提供。调用元类的
\uuuu new\uuuu
方法 当
Model
或创建任何子类(不是实例,而是类本身)时,允许元类任意修改类。 每个
模型
子类都包含有关其自身列的信息,并获取一个
对象
类属性,该属性用于查询数据库中的列

另外,如果模型类在models.base中,为什么要编写“models.Model”

models/\uuu init\uuu.py
models/base.py
导入
Model
,因此您不必编写
models.base.Model

模型类如何将模型属性转换为数据库列

模型
类本身并不真正进行任何转换。您创建了一个
Model
的子类,其中包含一些列信息, Django的ORM在构建与Django ORM查询相对应的数据库查询时使用的。转换是由数据库驱动程序在实际与特定数据库通信时完成的

这是一个行为有点像Django的
模型的玩具ORM
。如果您愿意,您可以实施
QuerySet
以获得乐趣:

class Column:
    '''
    Represents a database column.

    This is used to create the underlying table in the database
    and to translate database types to Python types.
    '''

    def __init__(self, type):
        self.type = type


class Manager:
    '''
    Accessed via `YourModel.objects`. This is what constructs
    a `QuerySet` object in Django.
    '''

    def __init__(self, model):
        self.model = model

    def get(self, id):
        '''
        Pretend `YourModel.objects.get(id=123)` queries the database directly.
        '''

        # Create an instance of the model. We only keep track of the model class.
        instance = self.model()

        # Populate the instance's attributes with the result of the database query
        for name in self.model._columns:
            # Pretend we load the values from the database
            value = 123
            setattr(instance, name, value)

        # This would be done above if we actually queried the database
        instance.id = id

        # Finally return the instance of `self.model`
        return instance


class ModelBase(type):
    def __new__(cls, name, bases, attrs):
        new_cls = super().__new__(cls, name, bases, attrs)

        # The `Manager` instance is made a class attribute
        new_cls.objects = Manager(new_cls)

        # Keep track of the columns for conveniece
        new_cls._columns = {}

        for name, attr in attrs.items():
            if isinstance(attr, Column):
                new_cls._columns[name] = attr

        # The class is now ready
        return new_cls


class Model(metaclass=ModelBase):
    '''
    Django's `Model` is more complex.
    This one only uses `ModelBase` as its metaclass so you can just inherit from it
    '''
    pass


class MyModel(Model):
    id = Column(int)
    column2 = Column(float)
    column3 = Column(str)


if __name__ == '__main__':
    print(MyModel._columns)

    instance = MyModel.objects.get(id=5)
    print(instance.id)
主要功能由
Model
作为元类提供。调用元类的
\uuuu new\uuuu
方法 当
Model
或创建任何子类(不是实例,而是类本身)时,允许元类任意修改类。 每个
模型
子类都包含有关其自身列的信息,并获取一个
对象
类属性,该属性用于查询数据库中的列

另外,如果模型类在models.base中,为什么要编写“models.Model”


models/\uuuu init\uuuuuu.py
models/base.py
导入
Model
,这样您就不必编写
models.base.Model

,我想更具体地了解Model类以及该类的功能。你知道为什么我必须写models.model,而model类似乎在models.base中吗?Django模型是Django的ORM不可分割的一部分。据我所知,您的问题是Django如何将您编写的模型转换为相应的SQL命令,并将其转换为DB中的表列。这个概念称为ORM(对象关系映射)。请在此处阅读:。如果您来自一种必须直接编写SQL命令的语言,这看起来可能很神奇,但Django将其抽象到Django模型库中。要解释Django模型的完整功能超出了范围,我想更具体地了解模型类以及该类的功能。你知道为什么我必须写models.model,而model类似乎在models.base中吗?Django模型是Django的ORM不可分割的一部分。据我所知,您的问题是Django如何将您编写的模型转换为相应的SQL命令,并将其转换为DB中的表列。这个概念称为ORM(对象关系映射)。请在此处阅读:。如果您来自一种必须直接编写SQL命令的语言,这看起来可能很神奇,但Django将其抽象到Django模型库中。要解释Django模型的完整功能超出了范围,您所说的“这是如何工作的”是什么意思?Django的ORM有很多很多部分