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 ...
随机推荐
- 使用Docsify做文档网站的详细配置教程
使用Docsify做文档网站的详细配置教程 作者:xhemj 没错,它叫Docsify. xhemj的文档中心就是用这个写的 开源地址:https://github.com/docsifyjs/doc ...
- 【转】Standardization(标准化)和Normalization(归一化)的区别
Standardization(标准化)和Normalization(归一化)的区别 https://blog.csdn.net/Dhuang159/article/details/83627146 ...
- netty实现群聊功能
[概述] 实现一个网络群聊工具.参与聊天的客户端消息是通过服务端进行广播的. 主要由两块组成:聊天服务器端(ChatServer)和聊天客户端(ChatClient). 聊天服务器(ChatServe ...
- RFID 有源,半源和无源的区别
RFID电子标签是由标签.解读器和数据传输和处理系统组成.内存带有天线的芯片,芯片中存储有能够识别目标的信息,主要作用都是为了识别货物.(更具体的自行搜索,本文单独讲三种的区别) RFID分为三种 有 ...
- 实验十一 MySQLl备份与恢复1
实验十一 MySQL备份与恢复 一. 实验内容: 1. 使用SQL语句导入和导出表数据 2. 使用客户端工具备份还原数据库 3. 使用日志文件恢复数据库 二. 实验项目:学生成绩数据库 创建用于学 ...
- 牛客寒假基础集训营 | Day1 E-rin和快速迭代(暴力 + 优化)
E-rin和快速迭代 题目描述 rin最近喜欢上了数论. 然而数论实在太复杂了,她只能研究一些简单的问题. 这天,她在研究正整数因子个数的时候,想到了一个"快速迭代"算法.设 f( ...
- 使用ElasticSearch赋能HBase二级索引 | 实践一年后总结
前言:还记得那是2018年的一个夏天,天气特别热,我一边擦汗一边听领导大刀阔斧的讲述自己未来的改革蓝图.会议开完了,核心思想就是:我们要搞一个数据大池子,要把公司能灌的数据都灌入这个大池子,然后让别人 ...
- Chrome截图截满滑动栏,QQ截长屏,录屏
1.Chrome截图截满滑动栏 一般我们截图都是用QQ的Ctrl+shift+A,但是网页不好截,这里我们可以用Chrome控制台来截全网页: F12或Ctrl+shift+i打开控制台: 点击一下控 ...
- MyBatis(三):核心配置文件的重要配置-Log
本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出1便就懂!b站搜索狂神说即可 https://space.bilibili.com/95256449?spm_id_from=333.788 ...
- H5 布局 -- 让容器充满屏幕高度或自适应剩余高度
在前端页面布局中,经常会碰到要让容器充满整个屏幕高度或者剩余屏幕高度的需求.一般这时候都会想当然的使用 height:100% 这样的 CSS 来写. 这样写的话,当容器内内容很多的时候是没有问题的, ...