原文网址
http://python.usyiyi.cn/django/intro/tutorial01.html
最好看过原文再阅读
model创建大致如下

#encoding=utf-8
from __future__ import unicode_literalsfrom django.db import models
from django.utils import timezone
import datetime class Question(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField('date published')def __str__(self):              # __unicode__ on Python 2return self.question_textdef was_published_recently(self):return self.pub_date >= timezone.now() - datetime.timedelta(days=1)class Choice(models.Model):question = models.ForeignKey(Question)choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)def __str__(self):              # __unicode__ on Python 2return self.choice_text     #the usage of this function:不仅会使你自己在使用交互式命令行时看得更加方便,而且会在Django自动生成的管理界面中使用对象的这种表示# three step of change models
# 1.修改你的模型(在models.py文件中)。
# 2.运行python manage.py makemigrations ,为这些修改创建迁移文件
# 3.运行python manage.py migrate ,将这些改变更新到数据库中。

使用python manage.py shell进行数据库操作

#encoding=utf-8
>>> from polls.models import Question, Choice   # Import the model classes we just wrote.# No questions are in the system yet.
#选择所有的Question
>>> Question.objects.all()
[]# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
#创建一个question对象
>>> q = Question(question_text="What's new?", pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.
#保存
>>> q.save()# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
#获取Question的一些属性
>>> q.id
1# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)#修改属性并保存
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()#再次查询所有Question
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
[<Question: Question object>]#=======================================================================>>> from polls.models import Question, Choice# 添加__str__()方法后再次查询所有Question
# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>]# 使用过滤器查询
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<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.# pk应该就是primary key的意思?
# 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)# 通过相关的Question对象显示与其有关的Choice对象集合---目前还没有相关的Choice对象
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]# 使用Question对象的Choice集合创建Choice对象
# 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对象也有一些API来访问与其相关的Question对象
# 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()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3# 查询一些Choice对象,这些Choice对象所属的Question对象的pub_date的年份为系统当前年份# 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)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]# 通过Question对象查询出Choice对象,删除
# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

Django使用Python操作数据库 --Django 1.8.2 文档(中文)部分笔记相关推荐

  1. HelloDjango 第 04 篇:Django 迁移、操作数据库

    文中涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库 我们已经编写了博客数据库模型的代码,但那还只是 Python 代码而已,django 还没有把它翻译成数据库语言,因此实际上这 ...

  2. Python操作数据库之 MySQL

    Python操作数据库之MySQL 一.安装Python-MySQLdb模块 Python-MySQLdb是一个操作数据库的模块,Python 通过它对 mysql 数据实现各种操作. 如果要源码安装 ...

  3. Python 操作数据库(1)

    在关系数据库中,数据库表是一系列二维数组的集合,用来代表和储存数据对象之间的关系.它由纵向的列和横向的行组成,例如一个有关作者信息的名为 authors 的表中,每个列包含的是所有作者的某个特定类型的 ...

  4. 表操作,数据操作,单表查询,python操作数据库

    1.表操作 创建 create table 删除 drop table 查看表结构 desc 表/show create table 表 修改 alter table 表名 rename 新表名 al ...

  5. python 操作数据库的常用SQL命令

    这俩天在学习PYTHON操作数据库的知识.其实基本SQL命令是与以前学习的MYSQL命令一致,只是增加了一些PYTHON语句. 1,安装pymysql,并导入. import pymysql 2,因为 ...

  6. Python学习笔记:使用Python操作数据库

    Python学习笔记:使用Python操作数据库 一.数据库编程接口 为了对数据库进行统一的操作,大多数语言都提供了简单的.标准化的数据库接口(API).在Python Database API 2. ...

  7. mybatisplus 操作另一个数据库的数据_实例分析:python操作数据库项目

    本文根据一个项目实例,记录分享一下python将数据库的内容提取显示到程序界面的过程及相关设置,探索python操作数据库的用法.主要分享内容:1.显示数据库内容.2.修改数据库内容.3.表格控件指定 ...

  8. Python操作数据库完成接口测试

    前言 数据库的操作在测试工作中也是经常使用的,通过一些一些工具来操作数据库的方法大家都应该了解,那么Python操作数据库的大家了解吗? 今天测试君通过本篇文章介绍下如何通过Python来操作mysq ...

  9. 五、使用Python操作数据库

    (六)使用Python操作数据 程序运行时,数据是在内存中.当程序终止时,通常需将数据保存在磁盘上.为了便于程序保存和读取数据,并能直接通过条件快速查询到指定数据,数据库(Database)这种专门用 ...

最新文章

  1. 【廖雪峰Python学习笔记】list tuple dict set
  2. 开发js插件之所遇--02[DOM]
  3. 石川es6课程---17、ES7 预览
  4. 你必须会的--Dijkstra算法--单源最短路径问题
  5. 1803无法升级到2004_今年的Win10更新很特别,不要随便升级!
  6. Java 12新功能完整指南
  7. 你愿意隐姓埋名一辈子吗?” #百年百人系列
  8. 【人脸识别终结者】多伦多大学反人脸识别,身份欺骗成功率达99.5%
  9. selenium自动化案例(一)B站专栏爬虫
  10. Android 音频开发(一) 基础入门篇
  11. php多进程结合Linux利器split命令实现把大文件分批高效处理
  12. NBA球队也使用Salesforce?
  13. 定义一个交通工具(Vehicle)的类
  14. 家政上门预约服务小程序源码+前端后端
  15. 服务器打不开网页dns错误是怎么回事,DNS错误原因是什么 如何解决DNS错误【详细介绍】...
  16. requests 用法
  17. 为什么要用MQ,MQ是什么?(消息队列)
  18. MATLAB DCT变换原理和源码
  19. 【C/C++】在Dos下(Dosbox)编写C/C++程序
  20. Java写单机版五子棋

热门文章

  1. Django周总结一
  2. 【Python3爬虫】当爬虫碰到表单提交,有点意思
  3. rest framework 节流
  4. 蓝桥杯 单点最短路径问题
  5. 从键盘上输入一个正整数n,请按照以下五行杨辉三角形的显示方式, 输出杨辉三角形的前n行。请采用循环控制语句来实现。...
  6. 根据条件控制参数控件是否显示(可用)
  7. 实现三联tab切换特效
  8. Javascript的继承
  9. poj 1039 Pipe (判断 直线和 线段 是否相交 并 求交点)
  10. UNICODE与ANSI的区别