编写views
views:作为MVC中的C,接收用户的输入,调用数据库Model层和业务逻辑Model层,处理后将处理结果渲染到V层中去。
polls/views.py:
|
1 2 3 4 5 |
|
编写urls
urls,程序的入口,支持正则匹配访问url,将访问url映射到views中的具体某个函数中。
为了能调用到上面这个views,我们需要将views.index函数映射到URL中。
我们可以创建一个urls.py 在App目录下。
polls/urls.py:
|
1 2 3 4 5 6 7 8 9 |
|
下一步,我们需要将创建的urls.py 添加到全局urls.py中,如
mysite/urls.py:
|
1 2 3 4 5 6 7 |
|
此时,可以通过访问 http://localhost:8000/polls/ 可以调用到所编写的views
编写models
models与数据库操作相关,是django处理数据库的一个特色之处,它包含你的数据库基本字段与数据。通过一系列封装的api可以直接操作数据库。当然,也支持原生sql。
既然models与数据库相关,那么首先需要配置数据库
1、数据库设置,mysite/settings.py:
这里默认使用内置的sqlite3,配置如下:
|
|
如果想要改为MYSQL,配置修改如下:
|
|
2、初始化数据库数据
$ python manage.py makemigrations $ python manage.py migrate
3、创建models
在本实例中,创建两个models:Questions 和 Choice.
polls/models.py:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
4、**models
将app包含到project中,我们需要将它的配置类注册到全局配置中的 INSTALLED_APPS 中。它的配置类 PollsConfig (自动生成)在 polls/apps.py 中,所以它的路径为'polls.apps.PollsConfig'
编辑mysite/settings.py:
|
|
现在,django已经知道包含了polls app。此时,我们需要告诉django,models已经更改。to create migrations for those changes
$ python manage.py makemigrations polls
运行后,控制台输出如:
然后,重新运行 python manage.py migrate,将会在数据库中创建这些models表。to apply those changes to the database.
$ python manage.py migrate
注意,每次更改models,都必须重新分别执行
$ python manage.py makemigrations $ python manage.py migrate
完善models
polls/models.py:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
修改位置:
通过Database API操作数据(测试models)
进入django shell 环境:
$ python manage.py shell
执行database API:
>>> from polls.models import Question, Choice # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>
# 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.
# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<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()
<QuerySet []>
# 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()
<QuerySet [<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)
<QuerySet [<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()