建立應用python
1 建立projectmysql
Django-admin startproject mysitesql
自動建立目錄結構:shell
mysite/ #項目容器數據庫
Manage.py #命令行工具django
mysite/ #項目文件api
__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.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index,name='index')
]
修改mysite/urls.py,添加以下內容:
from django.conf.urls import 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':'yue4512138',#密碼
'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.encoding import
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>]>