创建应用
1 创建project
Django-admin startproject mysite
自动创建目录结构:
mysite/ #项目容器
Manage.py #命令行工具
mysite/ #项目文件
__init__.py #定义包的空文件
Settings.py #配置文件
Urls.py #路由文件
Wsgi.py #提供底层网络通信
2 启动服务器
Python manage.py runserver
查看运行
3 创建应用程序
Python manage.py polls
4 编写视图
from django.test import TestCase
from django.http import HttpResponse
# Create your tests here.
def index(request):
return HttpResponse('Hello,word!You are at the polls index')
新建urls.py
from django.conf.urlsimport url
from . importviews
urlpatterns = [
url(r'^$',views.index,name='index')
]
修改mysite/urls.py,添加如下内容:
from django.conf.urlsimport include
urlpatterns = [
url(r'^polls/',include('polls.urls')),
]
启动服务器
Python manage.py runserver
通过浏览器查看
5 数据库安装
本示例使用的是mysql数据库.也可以使用其他,对应的配置如下:
Sqlite ’django.db.backends.sqlite3’
Postgresql ’django.db.backends.postgresql’,
Mysql ’django.db.backends.mysql’
Oracle ’django.db.backends.oracle’,
,修改mysite/setting.py,
DATABASES = {
'default': {
#sqlite
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#mysql
'ENGINE':'django.db.backends.mysql',#引擎
'NAME':'jkx',#数据库名
'USER':'root',#用户名
'PASSWORD':'123456',#密码
'HOST':'127.0.0.1',#数据库服务器ip
'PORT':'3306',#端口号
}
}
6 创建model模型
Polls/model.py
每个模型对应数据库中的一张表
'''
问题
'''
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)
7 注册应用
Mysite/settings.py
INSTALLED_APPS = [
'django.contrib.admin',#admin站点
'django.contrib.auth',#身份话证系统
'django.contrib.contenttypes',#内容类型框架
'django.contrib.sessions',#会话框架
'django.contrib.messages',#消息框架
'django.contrib.staticfiles',#静态文件管理框架
'polls.apps.PollsConfig'
]
重新生成模型的数据表结构,为改动创建迁移记录
python manage.py makemigrations polls
对数据库进行真正的迁移
Python manage.py sqlmigrate polls 0001
//在不丢失数据的同时,实时动态更新数据库
python manage.py migrate
8 使用api
D:\workspace_python\mysite>python manage.py shell
Python 3.6.0b2 (v3.6.0b2:b9fadc7d1c3f, Oct 10 2016, 20:36:51) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
>>> import django
>>> django.setup()#重启django
>>> from polls.models import Question,Choice#导入操作模块
>>> Question.objects.all()#查询question列表
<QuerySet []>
>>> from django.utils import timezone#导入模块
>>> q=Question(question_text="What is your name?",pub_date=timezone.now())#创建question对象
>>> q.save()#保存到数据库中
>>> q.id
1
>>> q.question_text
'What is your name?'
>>> q.pub_date
datetime.datetime(2016, 10, 21, 9, 34, 11, 36818, tzinfo=<UTC>)
>>> q.question_text='what is up?'#修改属性值
>>> q.save()#保存到数据库中
>>> Question.objects.all()#查询问题列表
<QuerySet [<Question: Question object>]>#看不到问题详细
需要修改model.py
两个模型中分别添加:
#想使用python2版本时才能使用
from django.utils.encodingimport
python_2_unicode_compatible
def __str__(self):#python2版本中使用的是__unique__
return self.question_text
def __str__(self):
return self.choice_text
修改完成后,重新启动shell
>>> from polls.models import Question,Choice
>>> Question.objects.all()
<QuerySet [<Question: what is up?>]>
>>> Question.objects.filter(id=1)
<QuerySet [<Question: what is up?>]>
>>> Question.objects.filter(question_text__startswith='what')
<QuerySet [<Question: what is up?>]>
>>> from django.utils import timezone
>>> current_year=timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What is your name?>
>>> Question.objects.get(id=2)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\Python36\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Python36\lib\site-packages\django\db\models\query.py", line 385, in get
self.model._meta.object_name
polls.models.DoesNotExist: Question matching query does not exist.
>>> q.choice_set.all()#查询关系集合
<QuerySet []>
#创建三个choice对象
>>> 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>
>>> q.choice_set.create(choice_text='Just hacking again',votes=0)
<Choice: Just hacking again>
>>> q.choice_set.all()#查询choice列表
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>