注册app
在setting.py中,写入自己创建的app,使django能够找到它
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
在app下的models.py文件中通过类操作数据库
from django.db import models
class UserInfo(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
python manage.py makemigrations
使数据库语句写入到app下的migrations文件夹下
python manage.py migrate
直接操作数据库
django默认数据库为sqlite3,通过更改settings.py更改数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'dbname',
'USER': 'root',
'PASSWORD': 'xxx',
'HOST': '',
'PORT': '',
}
}
# 由于Django内部连接MySQL时使用的是MySQLdb模块,
而python3中还无此模块,所以需要使用pymysql来代替
# 如下设置放置的与project同名的配置的 __init__.py文件中
import pymysql
pymysql.install_as_MySQLdb()
增删改查
from cmdb import models
def orm(request):
# 创建
# models.UserInfo.objects.create(username='alex', password=123)
# content = {'username': 'eric', 'password': 456}
# models.UserInfo.objects.create(**content)
# obj = models.UserInfo(username='merry', password='890')
# obj.save()
# 查
# result = models.UserInfo.objects.all()
# result = models.UserInfo.objects.filter(username='merry')
# print(result)
# for row in result:
# print(row.id, row.username, row.password)
# 删除
# models.UserInfo.objects.filter(username='merry').delete()
# 更新
models.UserInfo.objects.filter(id=1).update(username='root')
return HttpResponse("<h1>ok</h1>")