原文http://docs.djangoproject.com/en/1.2/intro/tutorial01/#intro-tutorial01
1.使用django-admin.py startproject project创建一个project
django-admin.py startproject mysite.在当前目录下创建了一个mysite目录
mysite目录包含下面四个文件
1>__init__.py:这是一个空文件,用来表示当前目录是一个包
2>manage.py:这是一个可以让你与Django project通过各种方式进行交互的命令行实用程序。后面我们会详细讲解
3>settings.py:用于设置django project。设置内容包括数据库连接,project所包含的app等等
4>urls.py。django project的url声明。
2。manag.py runserver ip port
manage.py runserver 80 #启动django server,会看到下面的界面
在地址栏输入:http://127.0.0.1,出现下面的结果说明配置成功。
3。配置数据库
打开settings.py,修改 DATABASES类似如下:
然后manage.py syncdb. 注意:上例中的数据库必须首先创建。
通过manage.py syncdb命令可以将你创建的app同步到数据库。
4。通过manage.py startapp appname创建app.
manage.py startapp polls# 会在当前目录下创建polls目录。polls目录下同样也包含四个文件
__init__.py,models.py,tests.py,views.py
编辑polls/models.py,使其内容如下:
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()
修改settings.py的INSTALLED_APPS部分,成为如下内容:
INSTALLED_APPS = (
' django.contrib.auth ' ,
' django.contrib.contenttypes ' ,
' django.contrib.sessions ' ,
' django.contrib.sites ' ,
' django.contrib.messages ' ,
' mysite.polls ' ,
)
运行manage.py validate检验是否有错误。如果出现"0 errors found".说明没有问题。
通过manage.py sql polls.可以查看同步到数据库时,将要执行的sql语句是什么.下图是sql语句
说明:1>这里的sql语句可能会因所用数据库的不同,sql语句会有所不同。
2>表名的确定。表名有appname_lower(model)组成。如例子中的appname为polls,model有poll和choice,所以表名
为polls_choice,polls_poll.
3>sql命令并没有真正的在数据库中执行,它只是输出django将要执行的sql语句。
4>通过上面的sql语句,我们看到django自动给每个表新增了逐渐字段id.
5>外键使用了modelname_id.如polls_choice表中的poll_id字段。
另:这里相关的命令还有:manage.py sqlcustom appname,manage.py sqlclear appname(根据数据库中表的存在情况,输出drop table所需的语句),manage.py sqlindexes appname(输出app的创建索引的sql语句),manage.py sqlall appname(是对sql,sqlcustom,sqlindexes的一个组合).
manage.py syncdb 同步到数据库
5.用API做一些尝试
运行manage.py shell. 注意这里不是python shell.我们首先来看一下manage.py shell做的设置。
>>> import sys
>>> sys.path
[ ' D:\\mysite ' , ' C:\\Python25\\lib\\site-packages\\babel-0.9.5-py2.5.egg ' , ' C:\\P
ython25\\lib\\site - packages\\trac - 0.11 . 7 .1dev - py2. 5 .egg ' , 。。。。]
>>> import os
>>> os.environ[ " DJANGO_SETTINGS_MODULE " ]
' mysite.settings '
manage.py shell做了两项工作:
1>将mysite添加到了sys.path里面
2>设置了环境变量DJANGO_SETTINGS_MODULE,环境变量指明了settings 的路径
>>> from mysite.polls.models import Poll,Choice
>>> # no polls are in the system yet
>>> Poll.objects.all()
>>> import datetime
>>> p=Poll(question="What's up?",pub_date=datetime.datetime.now())
>>> p.save()#保存对象到数据库,需要调用save()方法
>>> p.id
1L
>>> p.question #访问数据库列
"What's up?"
>>> p.pub_date #
datetime.datetime(2010, 8, 10, 10, 44, 56, 593000)
>>> p.pub_date=datetime.datetime(2010,8,10,0,0)
>>> p.save()
>>> p.pub_date
datetime.datetime(2010, 8, 10, 0, 0)
>>> Poll.objects.all()
[<Poll: Poll object>]
看到下面这里有点奇怪,
>>> Poll.objects.all()
[ < Poll: Poll object > ]
我们修改一下,编辑polls/models.py,修改成如下内容:
# coding:cp936
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length = 200 )
pub_date = models.DateTimeField( " date published " )
#新增__unicode__(self)方法
def __unicode__ (self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length = 200 )
votes = models.IntegerField()
#新增__unicode__(self)方法
def __unicode__ (self):
return self.choice
看效果:
>>> from mysite.polls.models import Poll
>>> Poll.objects.all()
[ < Poll: What ' s up?>]
下面再给Poll添加自定义的方法,was_published_today.
from django.db import models
import datetime
class Poll(models.Model):
question = models.CharField(max_length = 200 )
pub_date = models.DateTimeField( " date published " )
def __unicode__ (self):
return self.question
# 新增was_published_today方法
def was_published_today(self):
return self.pub_date.date() == datetime.datetime.today()
再次运行manage.py shell
>>> from mysite.polls.models import Poll,Choice
>>> Poll.objects.all() # 获取所有
[ < Poll: What ' s up?>]
>>> Poll.objects.filter(id = 1 ) # 查找方法,
[ < Poll: What ' s up?>]
>>> Poll.objects.filter(question__startswith = " What " ) # 查找方法,
[ < Poll: What ' s up?>]
>>> Poll.objects.get(pub_date__year = 2010 ) # 查找方法,
< Poll: What ' s up?>
>>> Poll.ojbects.get(id = 2 ) # 查找方法,这里id =2的Poll不存在
Traceback (most recent call last):
File " <console> " , line 1 , in < module >
AttributeError: type object ' Poll ' has no attribute ' ojbects '
>>> Poll.objects.get(id = 2 )
Traceback (most recent call last):
File " <console> " , line 1 , in < module >
File " C:\Python25\Lib\site-packages\django\db\models\manager.py " , line 132 , in
get
return self.get_query_set().get( * args, ** kwargs)
File " C:\Python25\Lib\site-packages\django\db\models\query.py " , line 341 , in g
et
% self.model._meta.object_name)
DoesNotExist: Poll matching query does not exist.
>>> Poll.objects.get(pk = 1 )
< Poll: What ' s up?>
>>> p = Poll.objects.get(pk = 1 )
>>> p.was_published_today() # 调用我们自定义的方法was_published_today
False
下面我们来看一下关系
>>> p.choice_set.all() # 查看该p对应的所有choice
[]
>>> p.choice_set.create(choice = " Not much " ,votes = 0) # 创建对应的choice
< 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)
>>> c.poll
< Poll: What ' s up?>
>>> p.choice_set.all()
[ < Choice: Not much > , < Choice: The sky > , < Choice: Just hacking again > ]
>>> p.choice_set.count() # 统计p的choice数目
3
>>> type(p.choice_set)
< class ' django.db.models.fields.related.RelatedManager ' >
>>> Choice.objects.filter(poll__pub_date__year = 2010 )
[ < Choice: Not much > , < Choice: The sky > , < Choice: Just hacking again > ]
>>> c = p.choice_set.filter(choice__startswith = " Just hacking " )
>>> c
[ < Choice: Just hacking again > ]
>>> c.delete() # 删除