码迷,mamicode.com
首页 > 其他好文 > 详细

02 - 看一眼Django都有啥

时间:2017-06-24 18:39:21      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:john   开发   xtend   recent   name   splay   创建数据库   oom   writing   

Django是源自于fast-paced newsroom environment

因此Django的目的就是为了使得web开发变得简单有效

下面的内容是一个用Django开发的a database-driven Web app

1 设计你的模型

  你可以使用没有数据库的Django

  但是如果使用数据库的话, 由于Django提供了ORM( object-relational mapper )这个能解决很多数据库问题的数据模型

  你可以

  mysite/news/models.py

from django.db import models

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __str__(self):              # __unicode__ on Python 2
        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):              # __unicode__ on Python 2
        return self.headline

2 根据这个模型创建数据库表

python manage.py migrate

  该命令执行的时候, 会查看所有可用的模型, 然后在数据库中创建相应不存在的表和optionally providing much richer schema control

3 使用Python代码操作数据库

  1) 导入

from news.models import Reporter, Article

  2) 查询所有内容, 返回的是QuerySet对象, 处理类似于集合的处理方式

表名.onjects.all()

>>> Reporter.objects.all()
<QuerySet [<Reporter: John Smith>]>

  查询指定列用get()

  传入的参数是一个表达式, 可以使用特殊__startswith, __contains来获取以开始, 包含

>>> 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>

  添加条件过滤用filter()

>>> Article.objects.filter(reporter__full_name__startswith=‘John‘)
<QuerySet [<Article: Django is cool>]>

  3) 新增数据

# Create a new Reporter.
>>> r = Reporter(full_name=‘John Smith‘)

# Save the object into the database. You have to call save() explicitly.
>>> r.save()

# Now it has an ID.
>>> r.id
1

>>> from datetime import date
>>> a = Article(pub_date=date.today(), headline=‘Django is cool‘,
...     content=‘Yeah.‘, reporter=r)
>>> a.save()

# Article objects get API access to related Reporter objects.
>>> r = a.reporter
>>> r.full_name
‘John Smith‘

  4) 删除数据

# Delete an object with delete().
>>> r.delete()

  对Repoter表的操作

技术分享
 1 # Import the models we created from our "news" app
 2 >>> from news.models import Reporter, Article
 3 
 4 # No reporters are in the system yet.
 5 >>> Reporter.objects.all()
 6 <QuerySet []>
 7 
 8 # Create a new Reporter.
 9 >>> r = Reporter(full_name=John Smith)
10 
11 # Save the object into the database. You have to call save() explicitly.
12 >>> r.save()
13 
14 # Now it has an ID.
15 >>> r.id
16 1
17 
18 # Now the new reporter is in the database.
19 >>> Reporter.objects.all()
20 <QuerySet [<Reporter: John Smith>]>
21 
22 # Fields are represented as attributes on the Python object.
23 >>> r.full_name
24 John Smith
25 
26 # Django provides a rich database lookup API.
27 >>> Reporter.objects.get(id=1)
28 <Reporter: John Smith>
29 >>> Reporter.objects.get(full_name__startswith=John)
30 <Reporter: John Smith>
31 >>> Reporter.objects.get(full_name__contains=mith)
32 <Reporter: John Smith>
33 >>> Reporter.objects.get(id=2)
34 Traceback (most recent call last):
35     ...
36 DoesNotExist: Reporter matching query does not exist.
对Repoter的操作

  对Article表的操作

技术分享
 1 # Import the models we created from our "news" app
 2 >>> from news.models import Reporter, Article
 3 
 4 # Create an article.
 5 >>> from datetime import date
 6 >>> a = Article(pub_date=date.today(), headline=Django is cool,
 7 ...     content=Yeah., reporter=r)
 8 >>> a.save()
 9 
10 # Now the article is in the database.
11 >>> Article.objects.all()
12 <QuerySet [<Article: Django is cool>]>
13 
14 # Article objects get API access to related Reporter objects.
15 >>> r = a.reporter
16 >>> r.full_name
17 John Smith
18 
19 # And vice versa: Reporter objects get API access to Article objects.
20 >>> r.article_set.all()
21 <QuerySet [<Article: Django is cool>]>
22 
23 # The API follows relationships as far as you need, performing efficient
24 # JOINs for you behind the scenes.
25 # This finds all articles by a reporter whose name starts with "John".
26 >>> Article.objects.filter(reporter__full_name__startswith=John)
27 <QuerySet [<Article: Django is cool>]>
28 
29 # Change an object by altering its attributes and calling save().
30 >>> r.full_name = Billy Goat
31 >>> r.save()
32 
33 # Delete an object with delete().
34 >>> r.delete()
对Article的操作

4 动态管理接口

  Django提供了功能完善的管理接口(administrative interface)

  需要在admin.py中添加配置

  mysite/news/admin.py

from django.contrib import admin

from . import models

admin.site.register(models.Article)

5 URLs的编写(URL调度程序)

  这个urls.py文件可以将URL的模式匹配与其相应的回调函数一一对应, 从而分离代码

  mysite/news/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r‘^articles/([0-9]{4})/$‘, views.year_archive),
    url(r‘^articles/([0-9]{4})/([0-9]{2})/$‘, views.month_archive),
    url(r‘^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$‘, views.article_detail),
]

  这些是一些正则匹配来匹配输入的URL

  正则表达式中的括号可以获取匹配成功的值

  匹配的过程是从前往后依次匹配, 一旦匹配成功, 就会调用相应的view函数处理, 如果到最后都还时没有匹配成功, 那么就会返回特殊的视图404

  传递给view函数的有一个请求对象, 和上述中括号正则表达式捕获到的值

/articles/2005/05/39323/
news.views.article_detail(request, ‘2005‘, ‘05‘, ‘39323‘)

6 编写视图(views)

  编写范例如下

  mysite/news/views.py

from django.shortcuts import render

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)

  最后返回的时候的html文件就用到了模板系统

7 编写模板

  在Django中可以设置一个目录列表, 里面有一个个存放模板的目录(具体设置方法)

  当查找模板的时候就依照顺序在这些目录中找

  具体模板文件有

  mysite/news/templates/news/year_archive.html

{% 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 %}

  具体语法有

  1) 值的获取

{{ year }}

  可以通过点的方式, 来进行属性查找, 字典的键查找, 索引查找 函数调用

{{ article.headline }}

  2) 模板过滤器(template filter)

  变量后面用 | 来进行一下处理的方式, 类似于linux中的管道

  格式化时间的方式如下

{{ article.pub_date|date:"F j, Y" }}

  还可以自定义模板过滤器, 自定义模板标签

  3) 模板继承

  基本模板( base templates )如下

  mysite/templates/base.html

{% load static %}
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <img src="{% static "images/sitelogo.png" %}" alt="Logo" />
    {% block content %}{% endblock %}
</body>
</html>

  继承代码为

{% extends "base.html" %} 

 

 

02 - 看一眼Django都有啥

标签:john   开发   xtend   recent   name   splay   创建数据库   oom   writing   

原文地址:http://www.cnblogs.com/weihuchao/p/7073769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!