这些文件是:
- __init__.py: 一个空文件,告诉python这个目录要被看作是python的包. (你可以阅读下python关于包的文档)
- manage.py: 一个命令行工具,让你和django进行各种不通的交互。
- settings.py: django配置文件.
- urls.py: 为django工程声明URL; 网站的地址目录
-
DATABASE_ENGINE -- 支持 'postgresql_psycopg2', 'mysql' , 'sqlite3'. 等
-
DATABASE_NAME -- 你的数据库名称,如果你用的是 SQLite, 填写你数据库文件路径; DATABASE_NAME 应该是个完整路径,包括文件名, 如果文件不存在, 第一次将会自动创建
-
DATABASE_USER -- 数据库的用户名,sqlite不需要
-
DATABASE_PASSWORD -- 数据库的密码,sqlite不需要
-
DATABASE_HOST -- 你的数据库主机. 如果在本机,这里可以不填 (sqlite不需要).
默认配置中, INSTALLED_APPS 包含了下面的应用, 都是来源django:
- django.contrib.auth -- 一个认证系统.
- django.contrib.contenttypes -- 一个内容类型架构.
- django.contrib.sessions -- 一个会话架构.
- django.contrib.sites -- 一个多站管理架构.
每个应用都至少用到一个数据表,因此我们需要先在数据库中创建表. 我们可以通过运行下面的命令来实现
syncdb 命令 会查看 INSTALLED_APPS 设置并创建必要的数据表根据数据库设置参数. 你将会看到每个数据表创建的信息,并且会提示你是否创建一个认证系统的超级管理账号,继续。。
如果你有兴趣,可以运行数据库的客户端来查看被创建的数据表
创建模型
- 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 = models.CharField(max_length=200)
- votes = models.IntegerField()
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 = models.CharField(max_length=200)
votes = models.IntegerField()
- INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'mysite.polls'
- )
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'mysite.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"),
- "choice" varchar(200) NOT NULL,
- "votes" integer NOT NULL
- );
- COMMIT;
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"),
"choice" varchar(200) NOT NULL,
"votes" integer NOT NULL
);
COMMIT;
- >>> from mysite.polls.models import Poll, Choice # 引入模型.
- # 系统里还没有投票.
- >>> Poll.objects.all()
- []
- # 创建投票.
- >>> import datetime
- >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
- # 把投票保存到数据库.
- >>> p.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.
- >>> p.id
- 1
- # Access database columns via Python attributes.
- >>> p.question
- "What's up?"
- >>> p.pub_date
- datetime.datetime(2007, 7, 15, 12, 00, 53)
- # 修改时间并保存.
- >>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
- >>> p.save()
>>> from mysite.polls.models import Poll, Choice # 引入模型.
# 系统里还没有投票.
>>> Poll.objects.all()
[]
# 创建投票.
>>> import datetime
>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
# 把投票保存到数据库.
>>> p.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.
>>> p.id
1
# Access database columns via Python attributes.
>>> p.question
"What's up?"
>>> p.pub_date
datetime.datetime(2007, 7, 15, 12, 00, 53)
# 修改时间并保存.
>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
>>> p.save()
- class Poll(models.Model):
- # ...
- def __unicode__(self):
- return self.question
- class Choice(models.Model):
- # ...
- def __unicode__(self):
- return self.choice
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
- import datetime
- # ...
- class Poll(models.Model):
- # ...
- def was_published_today(self):
- return self.pub_date.date() == datetime.date.today()
- 这里判断发布日期是否是今天,让我们再次进入交互命令模式。
- >>> from mysite.polls.models import Poll, Choice
- # 这里调用了 __unicode__() .
- >>> Poll.objects.all()
- [<Poll: What's up?>]
- # Django 提供一个充血数据库API
- # keyword arguments.
- >>> Poll.objects.filter(id=1)
- [<Poll: What's up?>]
- >>> Poll.objects.filter(question__startswith='What')
- [<Poll: What's up?>]
- # Get the poll whose year is 2007. Of course, if you're going through this
- # 查询2007年的投票.
- >>> Poll.objects.get(pub_date__year=2007)
- <Poll: What's up?>
- >>> Poll.objects.get(id=2)
- Traceback (most recent call last):
- ...
- DoesNotExist: Poll 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.
- # 获取主键为1的投票 Poll.objects.get(id=1).
- >>> Poll.objects.get(pk=1)
- <Poll: What's up?>
- # 调用自定义的方法.
- >>> p = Poll.objects.get(pk=1)
- >>> p.was_published_today()
- False
- # 为投票添加选项
- # choice object, does the INSERT statement, adds the choice to the set
- # of available choices and returns the new Choice object.
- >>> p = Poll.objects.get(pk=1)
- >>> p.choice_set.create(choice='Not much', votes=0)
- <Choice: Not much>
- >>> p.choice_set.create(choice='The sky', votes=0)
- <Choice: The sky>
- >>> c = p.choice_set.create(choice='Just hacking again', votes=0)
- # Choice objects have API access to their related Poll objects.
- >>> c.poll
- <Poll: What's up?>
- # 获取投票的所有选项.
- >>> p.choice_set.all()
- [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
- >>> p.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 poll whose pub_date is in 2007.
- >>> Choice.objects.filter(poll__pub_date__year=2007)
- [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
- # Let's delete one of the choices. Use delete() for that.
- >>> c = p.choice_set.filter(choice__startswith='Just hacking')
- >>> c.delete()
import datetime
# ...
class Poll(models.Model):
# ...
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
这里判断发布日期是否是今天,让我们再次进入交互命令模式。
>>> from mysite.polls.models import Poll, Choice
# 这里调用了 __unicode__() .
>>> Poll.objects.all()
[<Poll: What's up?>]
# Django 提供一个充血数据库API
# keyword arguments.
>>> Poll.objects.filter(id=1)
[<Poll: What's up?>]
>>> Poll.objects.filter(question__startswith='What')
[<Poll: What's up?>]
# Get the poll whose year is 2007. Of course, if you're going through this
# 查询2007年的投票.
>>> Poll.objects.get(pub_date__year=2007)
<Poll: What's up?>
>>> Poll.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Poll 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.
# 获取主键为1的投票 Poll.objects.get(id=1).
>>> Poll.objects.get(pk=1)
<Poll: What's up?>
# 调用自定义的方法.
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_today()
False
# 为投票添加选项
# choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object.
>>> p = Poll.objects.get(pk=1)
>>> p.choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky', votes=0)
<Choice: The sky>
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)
# Choice objects have API access to their related Poll objects.
>>> c.poll
<Poll: What's up?>
# 获取投票的所有选项.
>>> p.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> p.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 poll whose pub_date is in 2007.
>>> Choice.objects.filter(poll__pub_date__year=2007)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
# Let's delete one of the choices. Use delete() for that.
>>> c = p.choice_set.filter(choice__startswith='Just hacking')
>>> c.delete()