標籤:oob syn pps www. print 建立失敗 int ini 項目
官方教程點擊此處
項目預設使用sqlite
DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.sqlite3‘, ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘), }}
並且在根目錄中產生資料庫檔案
db.sqlite3
1.建立應用:官方規定,如果要使用模型,必須先建立一個app
python manage.py startapp ts
記得建立後去settings檔案中查看應用是否添加進去,沒有則自己添加,否則該應用中資料表建立失敗
INSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘ts‘)
2.在ts目錄中
migrations#目錄 __init__.py __init__.py admin.py models.py tests.py views.py
找到models檔案,在這裡面建立表
from django.db import models# Create your models here.class User(models.Model): name=models.CharField(max_length=64)
3.命令產生資料表:
python manage.py makemigrations
會自動知道我們的模型中的改變,並且開始建立資料庫(對於多個應用,會排除已經建立過的,對於新的,會執行這個操作)
Migrations for ‘ts‘: 0001_initial.py: - Create model User
開始建立資料表:
python manage.py migrate
Operations to perform: Synchronize unmigrated apps: staticfiles, messages Apply all migrations: sessions, admin, ts, auth, blog, contenttypesSynchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL...Running migrations: Rendering model states... DONE Applying ts.0001_initial... OK
建立成功
4.開始使用資料庫
from ts import models# Create your views here.def show_db(request): models.User.objects.create( name="test" ) ret=models.User.objects.all() for item in ret: print(item.name) return HttpResponse("<h1>test over</h1>")
記得在urls檔案中修改路由
from ts import views as v2
urlpatterns = [ url(r‘^test‘,v2.show_db)]
python---django使用資料庫