网址:https://docs.djangoproject.com/en/1.10/intro/tutorial02/

1.扫描installed_apps,创建需要的数据库table

python manage.py migrate

2.在APP中创建模板(models)

from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

3.安装一个app

# mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
...

4.对于model做出的变化更新

python manage.py makemigrations polls

python manage.py migrate

5.在控制台与app交互

python manage.py shell

6.设置时区(TIME_ZONE)

USE_TZ = False  #这个属性设置为false的时候就会使用本机时间,最好不要改成false
TIME_ZONE = 'Asia/Shanghai' #'UTC+8'

7.通过下面几个示例,了解models的使用(在shell模式下依次输入下面的语句):

from polls.models import Question, Choice

Question.objects.all()
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
q.question_text
q.pub_date
q.question_text = "What's up?"
q.save()
Question.objects.all()
#<QuerySet [<Question: Question object>]>

8.为models加入__str__等函数:

from django.db import models
import datetime
from django.utils import timezone # Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text

//Note the addition of import datetime and from django.utils import timezone, to reference Python’s standarddatetime module and Django’s time-zone-related utilities in django.utils.timezone, respectively. If you aren’t familiar with time zone handling in Python, you can learn more in the time zone support docs.

9.再次与改造好的API玩:

>>> from polls.models import Question, Choice

# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]> # Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]> # Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?> # Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist. # Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?> # Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True # Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1) # Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []> # Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) # Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?> # And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3 # The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]> # Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

上面感觉有很多值得继续钻研学习的地方,所以直接粘过来了。比如filter的使用,ForeignKey有什么效果,choice_set是怎么来的。还要以后细细研究。

For more information on model relations, see Accessing related objects. For more on how to use double underscores to perform field lookups via the API, see Field lookups. For full details on the database API, see our Database API reference.

这一节的GET到的新技能:数据库的基本使用,models对象的建立与基本使用。

经过两节的学习,得出结论:还是flask更好上手。。

Django官方文档学习2——数据库及模板的更多相关文章

  1. Django官方文档学习1——第一个helloworld页面

    Django 1.10官方文档:https://docs.djangoproject.com/en/1.10/intro/tutorial01/ 1.查看django版本 python -m djan ...

  2. django官方文档学习-入门part3创建用户视图

    一.官方的约定: 1.在django中有一个约定.那就是每一个app自己的模板最好放在自己app目录下的templates子目录下. 但是这个还没有完成.最好还是在templates目录下加一个app ...

  3. 喜大普奔!Django官方文档终于出中文版了

    喜大普奔!Django官方文档终于出中文版了 文章来源:企鹅号 - Crossin的编程教室 昨天经 Sur 同学告知才发现,Django 官方文档居然支持中文了! 之所以让我觉得惊喜与意外,是因为: ...

  4. Spring 4 官方文档学习(十一)Web MVC 框架

    介绍Spring Web MVC 框架 Spring Web MVC的特性 其他MVC实现的可插拔性 DispatcherServlet 在WebApplicationContext中的特殊的bean ...

  5. Spring 4 官方文档学习(十二)View技术

    关键词:view technology.template.template engine.markup.内容较多,按需查用即可. 介绍 Thymeleaf Groovy Markup Template ...

  6. Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC

    内容列表: 启用MVC Java config 或 MVC XML namespace 修改已提供的配置 类型转换和格式化 校验 拦截器 内容协商 View Controllers View Reso ...

  7. Spring Data Commons 官方文档学习

    Spring Data Commons 官方文档学习   -by LarryZeal Version 1.12.6.Release, 2017-07-27 为知笔记版本在这里,带格式. Table o ...

  8. Spring 4 官方文档学习(十一)Web MVC 框架之resolving views 解析视图

    接前面的Spring 4 官方文档学习(十一)Web MVC 框架,那篇太长,故另起一篇. 针对web应用的所有的MVC框架,都会提供一种呈现views的方式.Spring提供了view resolv ...

  9. Spring Boot 官方文档学习(一)入门及使用

    个人说明:本文内容都是从为知笔记上复制过来的,样式难免走样,以后再修改吧.另外,本文可以看作官方文档的选择性的翻译(大部分),以及个人使用经验及问题. 其他说明:如果对Spring Boot没有概念, ...

随机推荐

  1. PL/SQL 下邮件发送程序

    对DBA而言,尽管在os级别下发送邮件是轻而易举的事情,然而很多时候我们也需要在PL/SQL中来发送邮件,比如监控job的执行状况等.本文根据网友(源作者未考证)的代码将其改装并封装到了package ...

  2. 基于CentOS与VmwareStation10搭建Oracle11G RAC 64集群环境:1.资源准备

    最近,在VmwareStation 10虚拟机上,基于CentOS5.4安装Oracle 11g RAC,并把过程记录下来.刚开始时,是基于CentOS 6.4安装Oracle 11g RAC, 没有 ...

  3. 基于JavaScript的REST客户端框架

    现在REST是一个比较热门的概念,REST已经成为一个在Web上越来越常用的应用,基于REST的Web服务越来越多,包括Twitter在内的微博客都是用REST做为对外的API,先前我曾经介绍过“基于 ...

  4. vsftpd2.3.2安装、配置详解

    一.vsftpd 简介     Vsftpd是一个基于GPL发布的类UNIX系统的ftp服务器软件.其全称是Very Secure FTP Deamon,在安全性.速度和稳定性都有着不俗的表现.在安全 ...

  5. MySQL定期分析检查与优化表

    定期分析表   ANALYZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name]   本语句用于分析和存储表的关键字分布.在分析期间,使 ...

  6. IntelliJ IDEA svn 提交错误

    环境说明: 系统:Mac OS X 10.9 以及 10.10 系统设置:LANG=zh_CN.UTF-8 svn 客户端:1.8.10 IntelliJ IDEA 13 毫无疑问,IntelliJ ...

  7. 使用Thrift RPC编写程序(服务端和客户端)

    1. Thrift类介绍 Thrift代码包(位于thrift-0.6.1/lib/cpp/src)有以下几个目录: concurrency:并发和时钟管理方面的库processor:Processo ...

  8. windows7__32位下安装python2.6.6

    1.下载windows7__32位的python2.6.6.mis文件,直接运行.默认安装即可 2.设置系统环境变量,目的在cmd下能敲python后能够自动调用到安装目录程序 设计如下:(我的电脑- ...

  9. UNIX环境下用C语言写静态库与动态库

    静态库,动态库用UNIX 的术语来说,或者叫做归档文件(archive 常以.a 结尾)和共享对象(share object 常以lib 开头.so 结尾)更为准确.静态库,动态库可能是WINDOWS ...

  10. CSS 居中大全

    <center> text-align:center 在父容器里水平居中 inline 文字,或 inline 元素 vertical-align:middle 垂直居中 inline 文 ...