Home  >  Q&A  >  body text

python - from django.db import models 如何去理解?

from django.db import models

class User(models.Model):
    username = models.CharField(max_length = 30)
    headImg  = models.FileField(upload_to = './upload/')

    def __unicode__(self):
        return self.username

我看了下 django 的安装目录结构(http://d.pr/i/jkXN)。比较困惑的一个问题。

第一句代码的 models 从django目录结构看,应该是一个包。但是翻阅了下Python的一些教程在关于「模块化」那些章节都没有提到过这种方式(从一个包再import子包)。更多都是下面这么讲的:

form 包.子包 imort 模块

如果按照教材上讲的,第一句代码 models 就是一个模块。

而模块之于我一直的理解似乎就是一个文件/一个类。

思考越多,发现反而越乱,我知道肯定是哪里理解错了,所以恳请前辈帮忙指点迷津下。T_T

阿神阿神2742 days ago886

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 12:05:11

    The module can be a single file or a directory (because the structure of a relatively large module is not clear if it is written entirely in one file).

    Package means to wrap a group of modules to form a separate namespace. This avoids conflicts. For example, django is a namespace. Of course db is also a namespace. Even, models can be regarded as a namespace, and CharField belongs to the models namespace. From this perspective, django.db and django.db.models can also be called packages.

    But it is customary to call top level packages like django packages. You can understand it by looking at the Python package index.

    Also, it’s totally okay to call django a module. There is a website called Python Weekly Module, which specializes in introducing some excellent python packages.

    Django can also be called a library or a framework.

    In short, this is a matter of habit, so don’t worry too much.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 12:05:11

    The class django.db.models.Model is defined in django/db/models/base.py. You are too stuck on the concepts in the tutorial. Just do more exercises.

    Also, as @weakish said, this is just a matter of habit, don’t worry too much.

    reply
    0
  • PHPz

    PHPz2017-04-17 12:05:11

    First of all, django is a package, db is a sub-package of django, and models is also a package. Because there are __init__.py

    in its directory

    In addition, there is no Model in models. You can use syntax like models.Model because there is such a sentence in models of __init__.py:

    from django.db.models.base import Model
    

    Because this module indirectly imports this class, models.Model is legal.

    reply
    0
  • Cancelreply