python---django使用資料庫

來源:互聯網
上載者:User

標籤: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使用資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.