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.

猜你喜欢

转载自www.cnblogs.com/xunjishu/p/12757745.html