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 ...
随机推荐
- Java基础语法(4)-流程控制
title: Java基础语法(4)-流程控制 blog: CSDN data: Java学习路线及视频 1.程序流程控制 流程控制语句是用来控制程序中各语句执行顺序的语句,可以把语句组合成能完成一定 ...
- Prism 源码解读4-ViewModel注入
介绍 介绍一个Prism的MVVM实现,主要介绍Prism如何在WPF上进行的一些封装,以实现MVVM.MVVM到底是什么呢?看一下这一幅经典的图 以前没有ViewModel这个概念,就是将Model ...
- 【深度强化学习】Curriculum-guided Hindsight Experience Replay读后感
目录 导读 目录 正文 Abstract[摘要] Introduction[介绍] 导读 看任何一个领域的文章,一定要看第一手资料.学习他们的思考方式,论述逻辑,得出一点自己的感悟.因此,通过阅读pa ...
- DOM 操作成本到底高在哪儿?
从我接触前端到现在,一直听到的一句话:操作DOM的成本很高,不要轻易去操作DOM.尤其是React.vue等MV*框架的出现,数据驱动视图的模式越发深入人心,jQuery时代提供的强大便利地操作DOM ...
- Golang校招简历项目-简单的分布式缓存
前言 前段时间,校招投了golang岗位,但是没什么好的项目往简历上写,于是参考了许多网上资料,做了一个简单的分布式缓存项目. 现在闲下来了,打算整理下. github项目地址:https://git ...
- coding++:Java 中Model 与 实体的区别
model的字段>entity的字段,并且model的字段属性可以与entity不一致,model是用于前端页面数据展示的,而entity则是与数据库进行交互做存储用途. 举个例子: 比如在存储 ...
- python实现十大经典排序算法
Python实现十大经典排序算法 代码最后面会给出完整版,或者可以从我的Githubfork,想看动图的同学可以去这里看看: 小结: 运行方式,将最后面的代码copy出去,直接python sort. ...
- Spring - 事务管理概述
什么是事务管理? 第一个问题:什么是事务? 事务一般是相对数据库而言的,对于数据库一次操作就属于一个事务, 一次操作可以是几句 SQL 语句,也可以是若干行 JDBC 的 Java 语句.事务既然 ...
- Sublime Text 2 Install Package Debug
本文转载自CSDN空间freshlover的博客<Sublime Text 无法使用Package Control或插件安装失败的解决方法>,转载请注明出处,谢谢! Sublime Tex ...
- 数据源管理 | 基于JDBC模式,适配和管理动态数据源
本文源码:GitHub·点这里 || GitEE·点这里 一.关系型数据源 1.动态数据源 动态管理数据源的基本功能:数据源加载,容器维护,持久化管理. 2.关系型数据库 不同厂商的关系型数据库,提供 ...