默认情况下,配置使用sqlite。如果你是数据库新手,或者想尝试学习django,这是最简单的选择。sqlite包含在python,所以不需要安装任何东西来支持你的数据库。当开始你的第一个真正的项目,可能需要使用更强大的数据库如:postgresql,mysql等,可以配置数据库切换就可以了。
如果你不使用sqlite作为数据库,而使用其他设置,如user, password, 和 host 必须加入。欲了解更多详细信息,请参阅用于数据库的参考文档。
此外,请注意,在该文件的顶部的 installed_apps 设置。它包含了很多在本django示例中激活的所有 django 的应用程序的名称。 应用程序可以在多个项目中使用,你可以打包给别人并在他们的项目分发使用。
其中的一些应用程序使用至少一个数据库表,所以我们需要在数据库中创建的表才可以使用它们。要做到这一点,运行以下命令:
c:\python27\mysite>python manage.py migrate operations to perform: apply all migrations: admin, contenttypes, auth, sessions running migrations: rendering model states... done applying contenttypes.0001_initial... ok applying auth.0001_initial... ok applying admin.0001_initial... ok applying admin.0002_logentry_remove_auto_add... ok applying contenttypes.0002_remove_content_type_name... ok applying auth.0002_alter_permission_name_max_length... ok applying auth.0003_alter_user_email_max_length... ok applying auth.0004_alter_user_username_opts... ok applying auth.0005_alter_user_last_login_null... ok applying auth.0006_require_contenttypes_0002... ok applying auth.0007_alter_validators_add_error_messages... ok applying sessions.0001_initial... ok c:\python27\mysite>
migrate 命令着眼于installed_apps设置并创建根据您的 mysite/settings.py 文件数据库设置,并随应用程序数据库迁移任何数据库表(我们将在以后的教程讨论)。你会看到每个适用移植的消息。 如果有兴趣,运行命令行在你的数据库客户端,列如类型\dt (postgresql), show tables; (mysql), .schema (sqlite), 或 select table_name fromuser_tables; (oracle) 以显示django所创建的表。
在我们的简单调查的应用程序,我们将创建两个模型:question 和 choice。question有一个问题标题和发布日期。choice有两个字段:选择文本和票数。每个选项都与一个问题关联。
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)
该代码是直接的。每个模型是django.db.models.model类的子类。 每个模型具有许多类变量,每一个在模型变量与数据库表的字段关联。
每个字段由 field 类实例表示 – 例如,charfield表示字符型字段,datetimefield表示日期时间字段。这告诉django 每个字段保存的数据类型。
每个field实例(例如,question_text或pub_date)的名称是字段的名称,这是机器友好的格式。在python代码中使用这个值,数据库将使用它作为列名。
最后,需要注意的是关系的定义,这里使用了外键。这告诉 django 每个选项关联一个问题。 django支持所有常见的数据库关系:多对一,多对多以及一对之一。
installed_apps = [
'polls.apps.pollsconfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
c:\python27\mysite>python manage.py makemigrations polls
migrations for 'polls':
0001_initial.py:
- create model choice
- create model question
- add field question to choice
c:\python27\mysite>
迁移是django怎么存储您更改的模型(由你的数据库架构决定)- 它们只是在磁盘上的文件。您如果喜欢可以读取移植新的模型,它在文件 polls/migrations/0001_initial.py。你不会希望django每一次都读取它们,不过将它们设计成人可编辑的,你要知道django是如何变化的并手动调整。
还有将运行migrations,自动管理数据库模式(表)命令 - 这就是所谓的迁移,让我们看看sql了解移植运行。 sqlmigrate 命令将移植名称返回sql显示:
$ python manage.py sqlmigrate polls 0001
c:\python27\mysite>python manage.py sqlmigrate polls 0001
begin;
--
-- create model choice
--
create table "polls_choice" ("id" integer not null primary key autoincrement, "c
hoice_text" varchar(200) not null, "votes" integer not null);
--
-- create model question
--
create table "polls_question" ("id" integer not null primary key autoincrement,
"question_text" varchar(200) not null, "pub_date" datetime not null);
--
-- add field question to choice
--
alter table "polls_choice" rename to "polls_choice__old";
create table "polls_choice" ("id" integer not null primary key autoincrement, "c
hoice_text" varchar(200) not null, "votes" integer not null, "question_id" integ
er not null references "polls_question" ("id"));
insert into "polls_choice" ("choice_text", "votes", "id", "question_id") select
"choice_text", "votes", "id", null from "polls_choice__old";
drop table "polls_choice__old";
create index "polls_choice_7aa0f6ee" on "polls_choice" ("question_id");
commit;
c:\python27\mysite>
迁移命令将所有还没有被应用的迁移(django跟踪哪些是使用数据库中的一个特殊的表名为django_migrations应用)运行它们在数据库中 - 基本上是,将使用模型在数据库模式的变化同步。
c:\python27\mysite>python manage.py shell python 2.7.10 (default, may 23 2015, 09:44:00) [msc v.1500 64 bit (amd64)] on wi n32 type "help", "copyright", "credits" or "license" for more information. (interactiveconsole) >>>
只需键入“python” 来代替,因为manage.py设置django_settings_module环境变量,这给django python 导入路径到 mysite/settings.py文件。
>>> import django >>> django.setup()
>>> from polls.models import question, choice # import the model classes we just wrote. # no questions are in the system yet. >>> 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 >>> 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. >>> 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() # objects.all() displays all the questions in the database. >>> question.objects.all() [<question: question object>]这里需要等待一会儿. <question: question object>完全是这个对象的无用表示。让我们来解决这个问题:通过编辑question模型(在polls/models.py 文件),并添加一个__str__() 方法到这两个question 和 choice 模型:polls/models.py文件内容如下:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible # only if you need to support python 2
class question(models.model):
# ...
def __str__(self):
return self.question_text
@python_2_unicode_compatible # only if you need to support python 2
class choice(models.model):
# ...
def __str__(self):
return self.choice_text
注意,这些都是正常的python方法。让我们添加一个自定义的方法,这里只是为了演示:polls/models.py
import datetime
from django.db import models
from django.utils import timezone
class question(models.model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
注意这里增加 import datetime 和from django.utils import timezon,引用python的标准的datetime模块和django的时区相关的实用程序在django.utils.timezone,如果不熟悉在python的时区处理,可以阅读时区支持文档。
>>> from polls.models import question, choice
# 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.
# 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()
[]
# 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()
[<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)
[<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()
c:\python27\mysite> python manage.py createsuperuser
username: admin
email address: admin@h3.com
password: ********** password (again): ********* superuser created successfully.
c:\python27\mysite>python manage.py runserver
现在,打开web浏览器,进入“/admin/” 本地域名- 例如, http://127.0.0.1:8000/admin/ 应该看到管理员登录界面:

由于移在默认情况下开启,登录屏幕可能会显示在你自己的语言, 由于翻译在默认情况下开启,登录屏幕可能会显示在你自己的语言,
只有一件事要做:我们需要告诉管理员这个question对象有一个管理界面。要做到这一点,打开 polls/admin.py文件,并修改它如下:
from django.contrib import admin from .models import question admin.site.register(question)
点击“questions”。现在,在“change list”页面查看问题。该页面显示数据库中的所有问题,并允许您选择其中一个进行更改。还有我们先前创建的问题:

修改“date published”点击“today”和“now”快捷方式。然后点击“save and continue editing.”,然后点击“history”在右上角。你会看到一个页面,列出通过django管理到这个对象的所有变化,修改人用户名和时间戳:
代码下载:http://pan.baidu.com/s/1jgr3wdg


