Django文档阅读-Day1
Django文档阅读-Day1
Django at a glance
Design your model
from djano.db import models #数据库操作API位置
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
#print(obj)时输出对象的full_name
def __str__(self):
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField() #注意!!!
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) #外键
def __str__(self):
return self.headline
Install it
用Django命令行工具自动构建database tables。
python manage.py makemigrations
python manage.py migrate
Notes:
- The makemigrations command looks at all your available models and creates migrations for whichever tables don't already exist. migrate runs the migrations and creates tables in your database, as well as optionally much richer schema control.
- 我的理解:makemigrations 这条命令会检查所有可用的mode,并且为所有不存在的表创建migrations。之后migrate会运行这些migrations并在数据库中创建不存在的表
由于英语水平有限,我看官方3.0文档同时结合了一1.18版本的中文翻译文本,在这一步中其执行的是:
python manage.py syncdb
可见在后续版本中弃用。我猜测由一步分为两步的原因是:为了避免用户误操作
Enjoy the free API
The API is created on the fly, no code generation necessary:
这个API是自动生成的,不需要代码生成:
# Import the models we created from our "news" app
>>> from news.models import Article, Reporter
# No reporters are in the system yet.
>>> Reporter.objects.all()
<QuerySet []>
# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')
# Save the object into the database. You have to call save() explicitly.
>>> r.save() #基于对象的创建数据需要特别调用save方法。
# Now it has an ID.
>>> r.id
1
# Now the new reporter is in the database.
>>> Reporter.objects.all()
<QuerySet [<Reporter: John Smith>]>
# Fields are represented as attributes on the Python object.
#字段被表示成一个属性在Python对象中。
>>> r.full_name
'John Smith'
# Django provides a rich database lookup API.
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__startswith='John') #基于双下划线的模糊查询。
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__contains='mith')
<Reporter: John Smith>
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Reporter matching query does not exist.
# Create an article.
>>> from datetime import date #注意了,官方使用datetime库来操作时间而不是time
>>> a = Article(pub_date=date.today(), headline='Django is cool',
... content='Yeah.', reporter=r) #外键增加的方法之一。
>>> a.save() #基于对象创建的一定要调用save方法提交。猜测是就是调用COMMIT。
# Now the article is in the database.
>>> Article.objects.all()
<QuerySet [<Article: Django is cool>]>
# Article objects get API access to related Reporter objects.
>>> r = a.reporter
>>> r.full_name
'John Smith'
# And vice versa: Reporter objects get API access to Article objects.
>>> r.article_set.all() #反向查询。
<QuerySet [<Article: Django is cool>]>
# The API follows relationships as far as you need, performing efficient
# JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with "John".
>>> Article.objects.filter(reporter__full_name__startswith='John') #基于双下划綫的正向查询。
<QuerySet [<Article: Django is cool>]>
# Change an object by altering its attributes and calling save().
>>> r.full_name = 'Billy Goat' # update
>>> r.save()
# Delete an object with delete().
>>> r.delete() #delete
A dynamic admin interface: it's not just scaffolding - it's the whole house
admin 它不仅仅是一个脚手架!! 它是整个房子。
Once your models are defined, Django can automatically create a professional, production ready administrative interface– a website that lets authenticated users add, change and delete objects. The only step required is to register your model in the admin site:
from django.db import models #操作数据库API位置
#记得继承models模块下的Model类
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
from django.contrib import admin #admin的位置
from . import models
admin.site.register(models.Article) #注册需要管理的字段
The philosophy here is that your site is edited by a staff, or a client, or maybe just you – and you don’t want to have to deal with creating backend interfaces only to manage content.
One typical workflow in creating Django apps is to create models and get the admin sites up and running as fast as possible, so your staff (or clients) can start populating data. Then, develop the way data is presented to the public.
通常一个网站会有你的员工,客户或者只有你来编辑,但你可能并不想因此而去创建一个后台管理系统。
在一个创建Django应用的典型工作流中,首先需要创建模型并尽可能快地启动和运行admin sites,让你的员工(或者客户)能够开始录入数据。然后,才开始展现数据给公众的方式。
Design your URLs
A clean, elegant URL scheme is an important detail in a high-quality Web application. Django encourages beautiful URL design and doesn’t put any cruft in URLs, like .php or .asp.
To design URLs for an app, you create a Python module called a URLconf. A table of contents for your app, it contains a mapping between URL patterns and Python callback functions. URLconfs also serve to decouple URLs from Python code.
from django.urls import path
from . import views
urlpatterns = [
path('articles/<int:year>/', views.year_archive),
path('articles/<int:year>/<int:month>/', views.month_archive),
path('articles/<int:year>/<int:month>/<int:pk>/', views.article_detail),
]
The code above maps URL paths to Python callback functions (“views”). The path strings use parameter tags to “capture” values from the URLs. When a user requests a page, Django runs through each path, in order, and stops at the first one that matches the requested URL. (If none of them matches, Django calls a special-case 404 view.) This is blazingly fast, because the paths are compiled into regular expressions at load time.
Once one of the URL patterns matches, Django calls the given view, which is a Python function. Each view gets passed a request object – which contains request metadata – and the values captured in the pattern.
For example, if a user requested the URL “/articles/2005/05/39323/”, Django would call the function news.views.article_detail(request, year=2005, month=5, pk=39323).
类似于<int:year>是一个过滤器,会在URLs中捕捉匹配的值。当一个用户发出请求是,Django会按照顺序去匹配每一个模式,并停在第一个匹配请求的URL上。(如果没有匹配到,那么Django会返回404页面),这个过程是非常快的,因为加载时正则表达式已经在加载时编译好了。
Write your views
Each view is responsible for doing one of two things: Returning an HttpResponse object containing the content for the requested page, or raising an exception such as Http404. The rest is up to you.
Generally, a view retrieves data according to the parameters, loads a template and renders the template with the retrieved data. Here’s an example view for year_archive from above:
from django.shortcuts import render #render函数在这里哦,以后记住位置哦,shortcuts,回忆:admin在contrib里,models在db里,path在urls中。
from .models import Article
def year_archive(request, year):
a_list = Article.objects.filter(pub_date__year=year)
context = {'year': year, 'article_list': a_list} #传给模板系统渲染页面。
return render(request, 'news/year_archive.html', context)
This example uses Django’s template system, which has several powerful features but strives to stay simple enough for non-programmers to use.
Design your templates
The code above loads the news/year_archive.html template.
Django has a template search path, which allows you to minimize redundancy among templates. In your Django settings, you specify a list of directories to check for templates with DIRS. If a template doesn’t exist in the first directory, it checks the second, and so on.
Let’s say the news/year_archive.html template was found. Here’s what that might look like:
{% extends "base.html" %}
{% block title %}Articles for {{ year }}{% endblock %}
{% block content %}
<h1>Articles for {{ year }}</h1>
{% for article in article_list %}
<p>{{ article.headline }}</p>
<p>By {{ article.reporter.full_name }}</p>
<p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %}
{% endblock %}
在Django设置中,你可以指定一个查找模板的目录列表。如果一个模板没有在这个列表中,则会去找第二个。
Variables are surrounded by double-curly braces. {{ article.headline }} means “Output the value of the article’s headline attribute.” But dots aren’t used only for attribute lookup. They also can do dictionary-key lookup, index lookup and function calls.
Note {{ article.pub_date|date:"F j, Y" }} uses a Unix-style “pipe” (the “|” character). This is called a template filter, and it’s a way to filter the value of a variable. In this case, the date filter formats a Python datetime object in the given format (as found in PHP’s date function).
You can chain together as many filters as you’d like. You can write custom template filters. You can write custom template tags, which run custom Python code behind the scenes.
Finally, Django uses the concept of “template inheritance”. That’s what the {% extends "base.html" %} does. It means “First load the template called ‘base’, which has defined a bunch of blocks, and fill the blocks with the following blocks.” In short, that lets you dramatically cut down on redundancy in templates: each template has to define only what’s unique to that template.
Here’s what the “base.html” template, including the use of static files, might look like:
{% load static %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<img src="{% static "images/sitelogo.png" %}" alt="Logo">
{% block content %}{% endblock %}
</body>
</html>
Simplistically, it defines the look-and-feel of the site (with the site’s logo), and provides “holes” for child templates to fill. This means that a site redesign can be done by changing a single file – the base template.
It also lets you create multiple versions of a site, with different base templates, while reusing child templates. Django’s creators have used this technique to create strikingly different mobile versions of sites by only creating a new base template.
Note that you don’t have to use Django’s template system if you prefer another system. While Django’s template system is particularly well-integrated with Django’s model layer, nothing forces you to use it. For that matter, you don’t have to use Django’s database API, either. You can use another database abstraction layer, you can read XML files, you can read files off disk, or anything you want. Each piece of Django – models, views, templates – is decoupled from the next.
Django的创建者已经利用这个技术来创造了显著不同的手机版本的网站,只需要创建一个新的基础模板
This is just the surface
This has been only a quick overview of Django’s functionality. Some more useful features:
- A caching framework that integrates with memcached or other backends.
- A syndication framework that lets you create RSS and Atom feeds by writing a small Python class.
- More attractive automatically-generated admin features – this overview barely scratched the surface.
The next steps are for you to download Django, read the tutorial and join the community. Thanks for your interest!
今日收获单词
database-schema 数据库架构
technical specifics 技术细节
object-relational-mapper 对象映射表
access 访问
With that 接着
on the fly 动态
be created on the fly 被动动态生成
explictly /ɪkˈsplɪsɪtli/ 明确的,明白的
vice 恶习,缺点,卖淫
vice versa 反之亦然
behind the scenes 幕后
interface 接口,界面
scaffolding 脚手架 RMB:SCAF利人利己的-self centred altruism fad
production ready 生产可用性(可用于生产环境的)
administrative 管理的
administrative interface 管理界面
professional, production ready administrative interface.
专业的,可用于生产环境的管理界面。
contrib 普通发布版,软件库
philosophy 设计理念,哲学 RMB: 飞人(phi)跟我啰嗦(loso)哲学(philosophy)我气飞了(phy)
workflow 工作流
typical 典型的
populating data 展现数据
get up 启动
elegant 优雅的 RMB: 蚂蚁(ant)带上个(g)面具(ele),很是优雅(elegant)
scheme 计划,策划,方案
blazingly 强烈的,超级无敌的
blazing 燃烧的,耀眼的,炙热的,激烈的,情感强烈的
blaze 燃烧,发光,宣扬
The rest is up to you. 剩下的就靠你了
be up to 依靠于...
retrieve 检索,取回 RMB: 不断地(re)在树(tree)中检索(retrieve)字母i和v。
redundancy 冗余 re dun dancy RMB: 阿姨(re)炖(dun)蛋(dan)和草鱼(cy),这营养有点冗余(redundancy)啊
decouple 解耦 de couple RMB: 得嘞(de), 一对夫妻(couple)又被王默默拆散了(解耦)
serve to 有助于
double-curly braces 双花括号
curly adj.
Django文档阅读-Day1的更多相关文章
- Django文档阅读-Day2
Django文档阅读 - Day2 Writing your first Django app, part 1 You can tell Django is installed and which v ...
- Django文档阅读-Day3
Django文档阅读-Day3 Writing your first Django app, part 3 Overview A view is a "type" of Web p ...
- Django文档阅读之模型
模型 模型是您的数据唯一而且准确的信息来源.它包含您正在储存的数据的重要字段和行为.一般来说,每一个模型都映射一个数据库表. 基础: 每个模型都是一个 Python 的类,这些类继承 django.d ...
- 吴裕雄--天生自然PythonDjangoWeb企业开发:Django文档阅读简介
Django是基于MVC模式的框架,虽然也被称为“MTV”的模式,但是大同小异.对我们来说,需要了解的是无论是MVC模式还是MTV模式,甚至是其他的什么模式,都是为了解耦.把一个软件系统划分为一层一层 ...
- Django文档阅读之执行原始SQL查询
Django提供了两种执行原始SQL查询的方法:可以使用Manager.raw()来执行原始查询并返回模型实例,或者可以完全避免模型层直接执行自定义SQL. 每次编写原始SQL时都要关注防止SQL注入 ...
- Django文档阅读之聚合
聚合 我们将引用以下模型.这些模型用来记录多个网上书店的库存. from django.db import models class Author(models.Model): name = mode ...
- Django文档阅读之查询
创建对象 为了在Python对象中表示数据库表数据,Django使用直观的系统:模型类表示数据库表,该类的实例表示数据库表中的特定记录. 要创建对象,请使用模型类的关键字参数对其进行实例化,然后调用s ...
- Node.js的下载、安装、配置、Hello World、文档阅读
Node.js的下载.安装.配置.Hello World.文档阅读
- 我的Cocos Creator成长之路1环境搭建以及基本的文档阅读
本人原来一直是做cocos-js和cocos-lua的,应公司发展需要,现转型为creator.会在自己的博客上记录自己的成长之路. 1.文档阅读:(cocos的官方文档) http://docs.c ...
随机推荐
- Grid Illumination
2019-07-07 16:53:31 问题描述: 问题求解: 本题和n后问题很类似,所以最初的时候就直接套了n后的板子,MLE. public int[] gridIllumination(int ...
- shell编程之脚本参数$@,$*,$#,$$,$?的含义
#首先按顺序解释各个参数的含义 1.$0 表示脚本的文件名, 具体的路径信息和执行命令时的相对位置有关,例如 sakura@mi-OptiPlex-7050:~/sh$ sh args.sh arg ...
- 浅析二分搜索树的数据结构的实现(Java 实现)
目录 树结构简介 二分搜索树的基础知识 二叉树的基本概念 二分搜索树的基本概念 二分搜索树的基本结构代码实现 二分搜索树的常见基本操作实现 添加操作 添加操作初步实现 添加操作改进 查询操作 遍历操作 ...
- 避免自己写的 url 被diss!建议看看这篇RestFul API简明教程!
大家好我是 Guide 哥!这是我的第 210 篇优质原创!这篇文章主要分享了后端程序员必备的 RestFul API 相关的知识. RestFul API 是每个程序员都应该了解并掌握的基本知识,我 ...
- UNIX环境高级编程——TCP/IP网络编程 常用网络信息检索函数
UNIX环境高级编程——TCP/IP网络编程 常用网络信息检索函数 gethostname() getppername() getsockname() gethostbyname() ...
- 使用TensorFlow v2.0构建多层感知器
使用TensorFlow v2.0构建一个两层隐藏层完全连接的神经网络(多层感知器). 这个例子使用低级方法来更好地理解构建神经网络和训练过程背后的所有机制. 神经网络概述 MNIST 数据集概述 此 ...
- 斯坦福经典AI课程CS 221官方笔记来了!机器学习模型、贝叶斯网络等重点速查...
[导读]斯坦福大学的人工智能课程"CS 221"至今仍然是人工智能学习课程的经典之一.为了方便广大不能亲临现场听讲的同学,课程官方推出了课程笔记CheatSheet,涵盖4大类模型 ...
- 通过ISAPI http协议控制海康摄像头
一直用海康的SDK进行摄像头控制,但有时候非常不灵活,必须有X86的主机,在嵌入式上面就不行,通过写一个HTTPCLIENT可以通过ISAPI来控制海康的摄像头. 代码如下:git@github.co ...
- n次方
1.问题描述 计算 an 2.算法分析 先将 n 变一变,寻找新的计算路径.预处理就是变治法的根本. 如果单纯循环执行 n 次相乘,那么时间复杂度为 O(n).可以利用二进制幂大大改进效率. 主要思路 ...
- random方法
random.randint(1,10) # 产生 1 到 10 的一个整数型随机数 ,包括1和10random.random() # 产生 0 到 1 之间的随机浮点数rand ...