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
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 coursedb
is also a namespace. Even,models
can be regarded as a namespace, and CharField belongs to themodels
namespace. From this perspective,django.db
anddjango.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.
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.
First of all,
in its directorydjango
is a package,db
is a sub-package ofdjango
, andmodels
is also a package. Because there are__init__.py
In addition, there is no
Model
in models. You can use syntax likemodels.Model
because there is such a sentence inmodels
of__init__.py
:Because this module indirectly imports this class,
models.Model
is legal.