ORM可以帮助我们做两件事
create database gx_day15 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
settings.py文件中
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'gx_day15',
'USER':'root',
'PASSWORD':"123456",
"HOST":"127.0.0.1",
"PORT":"3306"
}
}
1.创建表:在app01/models.py文件中
from operator import mod
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name=models.CharField(max_length=32)
password=models.CharField(max_length=64)
age=models.IntegerField()
执行命令:
python manage.py makemigrations
python manage.py migrate
注意:app需要提前注册
2.添加表
class Department(models.Model):
title=models.CharField(max_length=16)
class Role(models.Model):
caption=models.CharField(max_length=16)
再次执行命令:
python manage.py makemigrations
python manage.py migrate
3.删除表
class Department(models.Model):
title=models.CharField(max_length=16)
#class Role(models.Model):
# caption=models.CharField(max_length=16)
再次执行命令:
python manage.py makemigrations
python manage.py migrate
4.删除表的字段
from operator import mod
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name=models.CharField(max_length=32)
password=models.CharField(max_length=64)
#age=models.IntegerField()
再次执行命令:
python manage.py makemigrations
python manage.py migrate
5.增加表的字段
from operator import mod
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name=models.CharField(max_length=32)
password=models.CharField(max_length=64)
#age=models.IntegerField()
# 1.没有默认值增加字段
# 执行命令会出现选项1和选项2,选择选项1,输入默认值
size=models.IntegerField()
# 2.有默认值增加字段
age=models.IntegerField(default=2)
# 3.增加字段允许内容为空
data=models.IntegerField(null=True,blank=True)
再次执行命令:
python manage.py makemigrations
python manage.py migrate
urls.py
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('orm/', views.orm),
]
views.py
#第一种引入方式,指定引入
from app01.models import Department,UserInfo
#第二种引入方式,引入全部
#from app01 import models
from django.shortcuts import render,HttpResponse,redirect
def orm(request):
# Department.objects.create(title="销售部")
# Department.objects.create(title="IT部")
# Department.objects.create(title="运营部")
#1.新建
UserInfo.objects.create(name="test",password="123456",age=20)
#2.删除
UserInfo.objects.filter(id=1).delete()
UserInfo.objects.all().delete()
#3.获取数据
#data_list=[对象,行,行] QuerySet类型
data_list=UserInfo.objects.all()
for obj in data_list:
print(obj.id,obj.name,obj.password,obj.age)
# 4.更新数据
UserInfo.objects.filter(id=1).update(age=999)
return HttpResponse("成功")
models.py
from operator import mod
from django.db import models
class UserInfo(models.Model):
name=models.CharField(max_length=32)
password=models.CharField(max_length=64)
age=models.IntegerField(default=2)
class Department(models.Model):
title=models.CharField(max_length=16)
访问127.0.0.1:8000/orm,返回成功