一篇文章带你梳理Python Django的正确学习方法!

Django是python的web开发框架,遵循MVC的设计模式,但在Django中通常称为MTV(model-template-views)。model是数据持久层,主要存放实体映射、实体关系以及实体的一些方法。template是表示层,主要是用来显示数据,Django的视图引擎可以将其渲染成HTML并显示。views是业务逻辑层,在Django中充当着链接model与template的桥梁,处理模型并向template提交数据,同时也接受template的请求和参数,完成相应的逻辑后提交模型修改。

个人认为这里的MTV和.NET MVC表达的是同一个意思,最大的差别就是在.net里views是表示层,而Django里是业务逻辑层,根据官方文档的意思只是对views的理解不一样而已,其实完全可以当成controller来用。下面我将根据个人的一些理解来介绍一下Django的语法和特色。

注:想学习Python的小伙伴们进群:984632579领取从0到1完整学习资料 视频 源码 精品书籍 一个月经典笔记和99道练习题及答案

!(http://upload-images.jianshu.io/upload_images/12650374-a2992ed2d436ed64?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

01,views和URL

views是业务逻辑层,在Django里面views通常是一个的views.py模块,放在对应的包里。views.py里面是具体的逻辑函数,每一个函数对应着一个或多个模版,为了建立模版与视图的联系,还要有一定的路由机制,于是Django通常在根目录有一个路由程序urls.py。路由由patterns来创建,用正则表达式来描述,极大地提高了路由机制的灵活性。

比如:

views.py

<pre class=”ql-align-justify” style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>def home(request):
values = request.META.items()
values.sort()
return render_to_response(‘home.html’,{“values”:values})
urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns(”,(‘^/pre>,home),)
</pre>

在这里request参数是必须的,但是你可以任意命名,只要符合规范即可,request包含页面的请求信息。sender_to_response在django.shortcuts里,所以你还要在前面声明form django.shortcuts import sender_to_response。request.MATE里含有所有的请求界面信息和用户信息。shor()是对list从小到大排序。返回值的意思就是向home.html模版提交一个values变量。urls中patterns中的元组添加了正则的导向规则:除去原地址匹配’^《一篇文章带你梳理Python Django的正确学习方法!》‘, home)就可以匹配/some/some/而some就会被传到处理函数home。相应的home要添加适当的参数来接受。

02,模版(Template)

模版在Django中是显示数据的地方,通常为HTML格式,在模版中Django的处理逻辑要写在{% %}中,而要显示的变量要写在{{ }}中。Django的母板页可以用任何文档充当,前提是要用{% block name %}{% endblock %}声明要填充或替换的块,而使用时只需{% extends 母版名字 %}然后调用相应的块就可以了。

03,模型

在setting.py 中的database的字典中配置数据库。配置完成后 使用manage.py startapp来创建app在models中编写python代码描述实体映射。比如:

models.py

<pre class=”ql-align-justify” style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>class Publisher(models.Model):
name = models.CharField(max_length = 30)
website = models.URLField()

def unicode(self):
return self.name

class Meta:
ordering = [‘name’]
</pre>

models包含在django.db中,里面封装了模型类的通用接口。CharField()是创建varchar型数据,参数有max_length,blank,verbose_name等。分别表示最大长度、是否为空、显示名称。def__unicode__提供了装箱后的默认显示,如果没有设置此函数,默认显示object类型。class Meta规定了模型的默认排序字段。同时Django也提供了外键设置接口,此处以book为例

<pre class=”ql-align-justify” style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>class Book(models.Model):
title = models.CharField(max_length = 100)
authors = models.ManyToManyField(Author) #多对多关系
publisher = models.ForeignKey(Publisher) #多对一关系
publication_date = models.DateField(blank = True, null = True)
</pre>

创建完成后要在setting.py配置文件INSTALL_APPS中加入app包的路径。

Django支持codefirst 可以用manage.py syncdb来同步数据库,更新数据库时Django是先生成sql语句然后再执行,在执行前可以运行manage.py validate来检查模型,也可以运行manage.py sqlall books。可以直接声明模型对象来实现数据的插入save()保存 objects.filter()查找,可以对象调用delete()删除,同时也可以模型调用delete批量删除。同理update也是对象调用单个修改,模型调用批量修改。

04,集成的子框架

在django.contrib包中有多种附加功能包,目前只了解了admin和auth两种感觉功能很强大,美中不足的是admin的界面略丑。 admin是Django官方提供的后台管理平台。可以管理你所添加的app集成了包括增删改查在内的所有常用功能。调用代码也很简单,只需要在urls.py内激活admin的链接即可,配置文件在setting.py里,有需求的话可以自行改动。如果想把app的管理加入里面需要添加如下代码(以Book为例):

<pre class=”ql-align-justify” style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>class BookAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘publisher’, ‘publication_date’) #显示顺序
list_filter = (‘publication_date’,) #过滤列表
ate_hierarchy = ‘publication_date’ #激活列表上方的日期查询
ordering = (‘-publication_date’,) #排序方式’-‘代表倒序
filter_horizontal = (‘authors’,) #添加时候的横向选择过滤(此处假设book和authors 是多对多关系)
raw_id_fields = (‘publisher’,) #添加时候的选择(此处假设publisher和book是一对多关系)

admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
admin.site.register(Book,BookAdmin)
</pre>

05,缓存机制

个人认为缓存对一个访问量过多的网站时非常重要的,Django里面提供的缓存方式大致分为三种:全站缓存配置方式,针对视图缓存配置方式,针对数据缓存配置方式。只要修改相关配置文件即可。也可以装其他插件来协助缓存,例如memcached。

    原文作者:编程新视野
    原文地址: https://www.jianshu.com/p/17a96f43554a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞