Django之models操作数据库
一、创建数据库及链接数据库
(1)在models.py中创建数据库
from django.db import models class UserInfo(models.Model): nid = models.AutoField(primary_key=True) user = models.CharField(max_length=30) email = models.EmailField()
(2)在settings.py里面注册app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cmdb' ]
(3) 在settings.py修改数据库连接
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
(4)执行命令生成数据库
python3 manage.py makemigrations python3 manage.py migrate
二、利用django的admin功能
(1)在admin.py中添加:
from django.contrib import admin from cmdb import models admin.site.register(models.UserInfo)
(2)创建一个超级用户
python3 manage.py createsuperuser
(3)在urls.py中指定url路由规则
urlpatterns = [ url(r'^admin/', admin.site.urls), ]
(4)启动django
gaochao$ c
(5)建立表的一对多关系