python---django使用数据库(orm)

官方教点击此处 

项目默认使用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)
  
   def __Str__(self):  #打印时直接打印数据,而不是显示类
     return self.name

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) ]

 

posted @ 2018-03-22 21:22  山上有风景  阅读(275)  评论(0编辑  收藏  举报