1. 程式人生 > >python---django使用數據庫

python---django使用數據庫

AC pan rate .sql 沒有 request eating spa sta

官方教程點擊此處

項目默認使用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, contenttypes
Synchronizing 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使用數據庫