1、手动创建数据库
create database orm;
2、在app/models.py里面创建一个类,继承models.Model
from django.db import models
class User(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
3、在django项目的settings.py里面配置数据库的相关信息
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'orm',
'USER':'root',
'PASSWORD':'root',
'HOST':'127.0.0.1',
'PORT':3306,
}
}
4、在django项目的init.py里面写上
import pymysql
pymysql.install_as_MySQLdb()
5、给django发布命令
python manage.py makemigrations
python manage.py migrage
注意如下:填写app名称
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app04'
]
结果如下:
mysql> show tables;
+----------------------------+
| Tables_in_orm |
+----------------------------+
| app04_user |
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
from django.shortcuts import HttpResponse, render, redirect
from . import models
def orm(request):
########查询###########
# 查询出所有的表数据
user_list = models.User.objects.all()
print(user_list)
print(user_list[0].id, user_list[0].username)
# 查询第一条
user0 = models.User.objects.first()
print("user0--->", user0.username)
# 过滤
user1 = models.User.objects.filter(username="saflyer")
print("user1", user1, user1[0].username)
# 拼字典
tmp = {"username": "saflyer"}
user2 = models.User.objects.filter(**tmp)
print(user2[0].username)
excludeList = models.User.objects.exclude(id=7)
print("exclude_list", excludeList)
# get用的少
# get0 = models.User.objects.get(id=1)
# print("get0",get0,get0.username)
########增加###########
new_user1 = models.User.objects.create(username="safly~~")
print("new_user", new_user1)
new_user2 = models.User(username="wuxxx")
new_user2.save()
########删除###########
deleUser = models.User.objects.filter(id=1).delete()
# dele (1, {'app04.User': 1})
print("dele", deleUser)
########修改###########
modifyUser = models.User.objects. \
filter(id=10).update(username="hhaha")
# modifyUser 1
print("modifyUser", modifyUser)
modifyUser1 = models.User.objects.filter(id=8).first()
modifyUser1.username = "一直花"
modifyUser1.save()
return render(request, "orm.html", {"user_list": user_list})
python manage.py makemigraions
python manage.py migrate app名称 --databse=配置文件数据名称的别名
手动操作:
models.UserType.objects.using('db1').create(title='普通用户')
result = models.UserType.objects.all().using('default')
自动操作:
class Router1:
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
return 'db1'
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
return 'default'
配置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'db1': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db1.sqlite3'),
},
}
DATABASE_ROUTERS = ['db_router.Router1',]
使用:
models.UserType.objects.create(title='VVIP')
result = models.UserType.objects.all()
print(result)
补充:粒度更细
class Router1:
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.model_name == 'usertype':
return 'db1'
else:
return 'default'
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
return 'default'
问题:
app01中的表在default数据库创建
app02中的表在db1数据库创建
#第一步:
python manage.py makemigraions
# 第二步:
app01中的表在default数据库创建
python manage.py migrate app01 --database=default
# 第三步:
app02中的表在db1数据库创建
python manage.py migrate app02 --database=db1
# 手动操作:
m1.UserType.objects.using('default').create(title='VVIP')
m2.Users.objects.using('db1').create(name='VVIP',email='xxx')
# 自动操作:
配置:
class Router1:
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.app_label == 'app01':
return 'default'
else:
return 'db1'
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
if model._meta.app_label == 'app01':
return 'default'
else:
return 'db1'
DATABASE_ROUTERS = ['db_router.Router1',]
使用:
m1.UserType.objects.using('default').create(title='VVIP')
m2.Users.objects.using('db1').create(name='VVIP',email='xxx')
数据库迁移时进行约束:
class Router1:
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
All non-auth models end up in this pool.
"""
if db=='db1' and app_label == 'app02':
return True
elif db == 'default' and app_label == 'app01':
return True
else:
return False
# 如果返回None,那么表示交给后续的router,如果后续没有router,则相当于返回True
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.app_label == 'app01':
return 'default'
else:
return 'db1'
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
if model._meta.app_label == 'app01':
return 'default'
else:
return 'db1'
setting中配置如下(根目录下):DATABASE_ROUTERS = [‘db_router.Router1’,]