1.简述
1.1 开发环境
该笔记所基于的开发环境为:windows8、python2.7.5、psycopg2-2.4.2、django1.5.4、pyCharm-2.7.3。以上所描述的软件、插件安装、破解等可以参考之前的python笔记,提供了具体的资源链接和操作步骤。
1.2 django学习笔记简介
django学习基于官网提供的投票应用,是学习该应用编写过程中,遇到的问题、知识点、注意问题等的总结,同时包含大量学习过程中的截图,方便大家更直观的学习。
它将包含两部分:
一个公共网站,可让人们查看投票的结果和让他们进行投票。
一个管理网站,可让你添加、修改和删除投票项目。
官网文档链接为http://django-chinese-docs.readthedocs.org/en/latest/
1.3 关于笔记
同样作为初学者,写这篇文章时,刚刚看到教程的第4部分,笔记中有不足之处,还希望大家指正,真心与大家共同讨论学习!
------------------------------------------------
博主经营一家发饰淘宝店,都是纯手工制作哦,开业冲钻,只为信誉!需要的亲们可以光顾一下!谢谢大家的支持!
店名:
小鱼尼莫手工饰品店
经营:
发饰、头花、发夹、耳环等(手工制作)
网店:
http://shop117066935.taobao.com/
---------------------------------------------------------------------
继续正题...
2.搭建项目的运行环境
import django; print(django.get_version())
django-admin.py startproject mysite
python manage.py syncdb
2.9.在pgadmin中查看创建好的tables
python manage.py startapp polls
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'polls',)
3.5 根据 model 的定义,使用命令语句获取创建table所需的sql
python manage.py sql polls BEGIN;CREATE TABLE "polls_poll" ( "id" serial NOT NULL PRIMARY KEY, "question" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL);CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);COMMIT;
3.6 再次运行 syncdb 命令,将会自动在你的数据库中创建这些模型对应的表
python manage.py syncdb
3.7 可以看到database中新创建了两个表
>>> from polls.models import Poll, Choice # Import the model classes we just wrote. # 系统中还没有 polls 。 >>> Poll.objects.all() [] # 创建一个新 Poll 。 # 在默认配置文件中时区支持配置是启用的,因此 Django 希望为 pub_date 字段获取一个 datetime with tzinfo 。使用了 timezone.now(),而不是 datetime.datetime.now() 以便获取正确的值。 >>> from django.utils import timezone >>> p = Poll(question="What's new?", pub_date=timezone.now()) # 保存对象到数据库中。你必须显示调用 save() 方法。 >>> p.save() # 现在对象拥有了一个ID 。请注意这可能会显示 "1L" 而不是 "1",取决于你正在使用的数据库。 这没什么大不了的,它只是意味着你的数据库后端喜欢返回的整型数作为 Python 的长整型对象而已。 >>> p.id 1# 通过 Python 属性访问数据库中的列。 >>> p.question "What's new?" >>> p.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>) # 通过改为属性值来改变值,然后调用 save() 方法。 >>> p.question = "What's up?" >>> p.save() # objects.all() 用以显示数据库中所有的 polls 。 >>> Poll.objects.all()[<Poll: Poll object>]
3.9 处理Poll object问题
class Poll(models.Model): # ... def __unicode__(self): return self.question class Choice(models.Model): # ... def __unicode__(self): return self.choice_text
ps:新shell演示,可以看到结果
import datetime from django.utils import timezone # ... class Poll(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
3.11 保存上访修改后,在新的shell中对table操作
python manage.py shell
>>> from polls.models import Poll, Choice # 确认我们附加的 __unicode__() 正常运行。 >>> Poll.objects.all() [<Poll: What's up?>] # Django 提供了一个丰富的数据库查询 API ,完全由关键字参数来驱动。 >>> Poll.objects.filter(id=1) [<Poll: What's up?>] >>> Poll.objects.filter(question__startswith='What') [<Poll: What's up?>] # 获取今年发起的投票。 >>> from django.utils import timezone >>> current_year=timezone.now().year >>> Poll.objects.get(pub_date__year=current_year) <Poll: What's up?> # 请求一个不存在的 ID ,这将引发一个异常。 >>> Poll.objects.get(id=2) Traceback (most recent call last): ...DoesNotExist: Poll matching query does not exist. Lookup parameters were {'id': 2} # 根据主键查询是常见的情况,因此 Django 提供了一个主键精确查找的快捷方式。 # 以下代码等同于 Poll.objects.get(id=1). >>> Poll.objects.get(pk=1) <Poll: What's up?> # 确认我们自定义方法正常运行。 >>> p = Poll.objects.get(pk=1) >>> p.was_published_recently() True # 给 Poll 设置一些 Choices 。通过 create 方法调用构造方法去创建一个新Choice 对象实例,执行 INSERT 语句后添加该 choice 到可用的 choices 集中并返回这个新建的 Choice 对象实例。 Django 创建了一个保存外键关联关系的集合 ( 例如 poll 的 choices) 以便可以通过 API去访问。 >>> p = Poll.objects.get(pk=1) # 从关联对象集中显示所有 choices -- 到目前为止还没有。 >>> p.choice_set.all()[] # 创建三个 choices 。 >>> p.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> >>> p.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> >>> c = p.choice_set.create(choice_text='Just hacking again', votes=0) # Choice 对象拥有访问它们关联的 Poll 对象的 API 。 >>> c.poll <Poll: What's up?> # 反之亦然: Poll 对象也可访问 Choice 对象。 >>> p.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] >>> p.choice_set.count() 3 # 只要你需要 API 会自动连续关联。使用双下划线来隔离关联。只要你想要几层关联就可以有几层关联,没有限制。 # 寻找和今年发起的任何 poll 有关的所有 Choices( 重用我们在上面建立的 'current_year' 变量 )。 >>> Choice.objects.filter(poll__pub_date__year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] # 让我们使用 delete() 删除 choices 中的一个。 >>> c = p.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete()
结果(ps:delete 后 The haking行删除)