Django入门笔记【一】

入门笔记翻译整理自:https://docs.djangoproject.com/en/1.8/

*该笔记将使用一个关于投票网络应用(poll application)的例子来阐述Django的用法。

1. 查看Django是否安装及版本

 1 $ python -c "import django; print(django.get_version())" 

2. 创建一个项目(project)

通过cd方式进入自创目录,然后运行:

 1 $ django-admin startproject mysite 

这将创建一个名为mysite的项目:

1 mysite/
2     manage.py
3     mysite/
4         __init__.py
5         settings.py
6         urls.py
7         wsgi.py

3. 数据库设置(database setup)

在数据库中创建表格:

 1 $ python manage.py migrate 

4. 开发服务器(development server)

进入mysite目录,并运行

 1 $ python manage.py runserver 

也可以指名地址和端口

 1 $ python manage.py runserver 0.0.0.0:8000 

5. 创建模型(models)

在manage.py所在文件夹中,创建投票网络应用

 1 $ python manage.py startapp polls 

文件夹结构如下:

1 polls/
2     __init__.py
3     admin.py
4     migrations/
5         __init__.py
6     models.py
7     tests.py
8     views.py

编辑polls/models.py:

 1 #polls/models.py
 2 
 3 from django.db import models
 4 
 5 class Question(models.Model):
 6     question_text = models.CharField(max_length=200)
 7     pub_date = models.DateTimeField('date published')
 8 
 9 class Choice(models.Model):
10     question = models.ForeignKey(Question)
11     choice_text = models.CharField(max_length=200)
12     votes = models.IntegerField(default=0)

6. 激活模型

Django应用是可插拔的(pluggable),在mysite/settings.py中插入polls应用

 1 #mysite/settings.py
 2 
 3 INSTALLED_APPS = (
 4     'django.contrib.admin',
 5     'django.contrib.auth',
 6     'django.contrib.contenttypes',
 7     'django.contrib.sessions',
 8     'django.contrib.messages',
 9     'django.contrib.staticfiles',
10     'polls',
11 )

然后运行代码

1 $ python manage.py makemigrations polls

这会创建文件polls/migrations/0001_initial.py

然后运行代码

1 $ python manage.py sqlmigrate polls 0001

这会显示(但并不创建)Django认为polls所需要的数据库表格

运行代码

1 $ python manage.py migrate

这会创建polls所需要的数据库表格。

7. 使用API

使用manage.py初始化python

1 $ python manage.py shell

进入python shell,就可以开始探索数据库API

 1 >>> from polls.models import Question, Choice
 2 
 3 # No questions are in the system yet
 4 >>> Question.objects.all()
 5 []
 6 
 7 # Create a new Question
 8 >>> from django.utils import timezone
 9 >>> q = Question(question_text="What's new?", pub_date=timezone.now())
10 
11 # Save the object into database
12 >>> q.save()
13 
14 # The object has an ID
15 >>> q.id
16 1
17 
18 # Access model field values via Python attributes
19 >>> q.question_text
20 "What's new?"
21 >>> q.pub_date
22 datetime.datetime(2012, 2, 26,13, 0, 0, 775217, tzinfo=<UTC>)
23 
24 # Change values by changing the attributes
25 >>> q.question_text = "What's up?"
26 >>> q.save()
27 
28 # object.all() displays all the questions in the database
29 >>> Question.objects.all()
30 [<Question: Question object>]

无疑,最后的返回值<Question: Question object>不包含任何信息量。尝试对Question和Choice加入__str__()方法来改进:

 1 # polls/models.py
 2 from django.db import models
 3 
 4 class Question(models.Model):
 5     # ...
 6     def __str__(self):        #__unicode__ on Python 2
 7         return self.question_text
 8 
 9 class Choice(models.Model):
10     # ...
11     def __str__(self):        #__unicode__ on Python 2
12         return self.choice_text

__str__()和__unicode__()都是Python自带方法,我们可以自定义一个方法:

 1 # polls/models.py
 2 
 3 import datetime
 4 
 5 from django.db import models
 6 from djangol.utils import timezone
 7 
 8 class Question(models.Model):
 9     # ...
10     def was_published_recently(self):
11         return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

将这些修改保存,并重新运行 python manage.py shell 

 1 >>> from polls.models import Question, Choice 
 2 
 3 # Make sure our __str__() addition worked.
 4 >>> Question.objects.all()
 5 [<Question: What's up?>]
 6 
 7 # Django provides a rich database lookup API
 8 >>> Question.objects.filter(id=1)
 9 [<Question: What's up?>]
10 >>> Question.objects.filter(question_text__startswith='What')
11 [<Question: What's up?>]
12 
13 # Get the question that published this year
14 >>> from django.utils import timezone
15 >>> current_year = timezone.now().year
16 >>> Question.objects.get(pub_date__year=current_year)
17 <Question: What's up?>
18 
19 # Request an ID that doesn't exist, this will raise an exception
20 >>> Question.objects.get(id=2)
21 
22 # Lookup by a primary key, identical to Question.objects.get(id=1)
23 >>> Question.objects.get(pk=1)
24 <Question: What's up?>
25 
26 # Make sure our custom method worked
27 >>> q = Question.objects.get(pk=1)
28 >>> q.was_published_recently()
29 True

为问题创建选项:

 1 # Give the Question a couple of Choices. 
 2 >>> q = Question.objects.get(pk=1)
 3 
 4 # Display any choices from the related object set
 5 >>> q.choice_set.all()
 6 []
 7 
 8 # Create three choices
 9 >>> q.choice_set.create(choice_text='Not much', votes=0)
10 <Choice: Not much>
11 >>> q.choice_set.create(choice_text='The sky', votes=0)
12 <Choice: The sky>
13 >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
14 
15 # Choice objects have API access to their related Question objects
16 >>> c.question
17 <Question: What's up?>
18 
19 # And vice versa: Question objects get access to Choice objects
20 >>> q.choice_set.all()
21 [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
22 >>> q.choice_set.count()
23 3
24 
25 # Use double underscores to separate relationships. 
26 >>> Choice.objects.filter(question__pub_date__year=current_year)
27 [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
28 
29 # Delete one of the choices
30 >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
31 >>> c.delete()

--The end--

原文地址:https://www.cnblogs.com/py-drama/p/4579476.html