Django特性

  • ORM。models层建立数据类与数据库中数据形成ORM映射关系

  • MTV架构。与MVC架构有小小的区别,controller的功能被分化在了url dispatcher(urls.py文件)与views两个模块中

目录结构

Django把一个网站所有内容称作一个project,每个模块称作app

例如如下目录结构中,项目名称mysite为一个project, 文件夹mysite/mysite称为项目的根配置文件,其中的文件mysite/mysite/urls.py提供了url的一级路由,路由到各个app中,例如polls这个app

mysite/manage.pymysite/__init__.pysettings.pyurls.pyasgi.pywsgi.pypolls/__init__.pyadmin.pyapps.pymigrations/__init__.py0001_initial.pymodels.pystatic/polls/images/background.gifstyle.csstemplates/polls/detail.htmlindex.htmlresults.htmltests.pyurls.pyviews.pytemplates/admin/base_site.html

部分模块功能解释如下

mysite\mysite\settings.py: 项目的配置项,类似于maven,有着如下形式的内容

from pathlib import Path# Build paths inside the project like this: BASE_DIR / 'subdir'.BASE_DIR = Path(__file__).resolve().parent.parent# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'django-insecure-#3+p28vqi&m@pj(ito4frk2%57ic^27cn@ip-i4vu(4)z6ow43'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = ['polls.apps.PollsConfig','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF = 'mysite.urls'TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [],'APP_DIRS': True,'OPTIONS': {'context_processors': ['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},},]WSGI_APPLICATION = 'mysite.wsgi.application'# Database# https://docs.djangoproject.com/en/3.2/ref/settings/#databasesDATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3','NAME': BASE_DIR / 'db.sqlite3',}}# Password validation# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',},{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',},{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',},]

mysite\mysite\urls.py

我把它称作根路由或一级路由。之所以这么取名,因为在每个所谓app中,还有第二级url控制器

架构

用户从最右侧开始访问,请求(url)首先进入根目录下的url控制器(或称url dispatcher)中。url dispatcher中有着如下形式的函数

urlpatterns = [path('polls/', include('polls.urls', namespace="polls")),path('admin/', admin.site.urls),# django提供的管理工具]

这个url控制器可以称为一级路由。提供了project到app的映射

进入某个app后,还有二级路由,有着如下形式

from django.urls import pathfrom . import viewsapp_name = 'polls'urlpatterns = [path('', views.IndexView.as_view(), name='index'),path('/', views.DetailView.as_view(), name='detail'),path('/results/', views.ResultsView.as_view(), name='results'),path('/vote/', views.vote, name='vote'),]

可见,它提供了app到view层函数的映射

映射到view层某个函数(例如下面的”vote函数”),view会调用models层的数据与templates层的模板,render一个完整的页面返回给用户,有着如下的形式

def vote(request, question_id):question = get_object_or_404(Question, pk=question_id)try:selected_choice = question.choice_set.get(pk=request.POST['choice'])except (KeyError, Choice.DoesNotExist):# Redisplay the question voting form.return render(request, 'polls/detail.html', {'question': question,'error_message': "You didn't select a choice.",})else:selected_choice.votes += 1selected_choice.save()# Always return an HttpResponseRedirect after successfully dealing# with POST data. This prevents data from being posted twice if a# user hits the Back button.return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

可以看出,views层与url dispatcher共同承担了controller层的作用。在架构图中也可以看出,views层可以叫做django数据处理的中心模块也不为过

Models层中建立了一些POCO类,这些POCO类与数据库中的数据形成ORM映射,从而进行各种操作,示例代码如下

# Create your models here.from django.db import modelsclass Question(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField('date published')class Choice(models.Model):question = models.ForeignKey(Question, on_delete=models.CASCADE)choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)

templates层也就是一些html文件,形式类似于jsp,例如下面这段代码

注意{% code %}中写逻辑代码,{{}}中写变量代码

<h1>{{ question.question_text }}</h1><ul>{% for choice in question.choice_set.all %}<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>{% endfor %}</ul><a href="{% url 'polls:detail' question.id %}">Vote again?</a>{% endfor %}</ul><a href="{% url 'polls:detail' question.id %}">Vote again?</a>

参考

  • django架构
  • django官方教程