ORM ,全稱 Object Relational Mapping ,中文叫做對象關系映射,通過 ORM 我們可以通過類的方式去操作數據庫,而不用再寫原生的SQL語句.通過把表映射成類,把行作實例,把字段作為屬性, ORM 在執行對象操作的時候最終還是會把對應的操作轉換為數據庫原生語句.使用 ORM 有許多優點:
將 ORM 模型映射到數據庫中,總結起來就是以下幾步:
(pip install dajngo)
一般將需要的包以及版本寫入文本批量安裝,方便環境遷移
eg:
Django==1.11.15
django-celery==3.2.2
django-cors-headers==2.4.0
django-crispy-forms==1.7.2
django-filter==1.0.4
elasticsearch==6.3.1
pymongo==3.7.1
PyMySQL==0.9.2
命令
pip install -r requirement.txt
創建之前先cdChange to the directory where the project is stored
django-admin startproject fault # 工程項目名
python manage.py startapp core # 子應用名字
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
]
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
"ENGINE": "django.db.backends.mysql",
"NAME": "fault",
"USER": "root",
"PASSWORD": "123456",
"HOST": "172.17.161.77",
"PORT": "",
}
}
也可以寫入chaos.conf文件,然後在settings.py配置:
# mysql
CONFIG_FILE = '/etc/ptms/chaos.conf'
try:
execfile(CONFIG_FILE)
except IOError as e:
print('Skipping settings loading, no file at %s' % CONFIG_FILE)
except SyntaxError as e:
print('Invalid syntax in configuration at %s' % CONFIG_FILE)
raise e
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
python manage.py makemigrations core(Uncheck the app name and generate all)
python manage.py migrate
python manage.py sqlmigrate core(子應用名) 0001
python manager.py createsuperuser
Then follow the prompts to enter a username(username),郵箱(Email),密碼(password),再次輸入密碼.
python manager.py runserver 0.0.0.0:8000
url.pyDefault is configuredadminManage routing in the background
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^api/admin/', admin.site.urls),
]
http://localhost:8080/admin
Use the newly created administrator account,Can enter the project background
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
"""
index視圖
:param request: 包含了請求信息的請求對象
:return: 響應對象
"""
return HttpResponse("hello the world!")
def testUpfile(request):
"""
render 渲染
"""
if request.method == "GET":
return render(request, "upload.html")
納入url路由
from django.conf.urls import url
from django.contrib import admin
from core.views import testUpfile, index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/test', testUpfile),
url(r'^index', index),
]
然後按照ORM映射在appIt is necessary to develop the business on the application.