14.2ORM
ORM可以帮助我们做两件事
- 创建,修改,删除数据库中的表(不用你写SQL语句)
- 操作表中的数据(不用写SQL语句)
14.2.1创建数据库
create database gx_day15 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
14.2.2django连接数据库
settings.py文件中
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'gx_day15',
'USER':'root',
'PASSWORD':"123456",
"HOST":"127.0.0.1",
"PORT":"3306"
}
}
14.2.3django操作表
1.创建表:在app01/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()
执行命令:
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)
再次执行命令:
python manage.py makemigrations
python manage.py migrate
4.删除表的字段
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)
再次执行命令:
python manage.py makemigrations
python manage.py migrate
5.增加表的字段
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)
size=models.IntegerField()
age=models.IntegerField(default=2)
data=models.IntegerField(null=True,blank=True)
再次执行命令:
python manage.py makemigrations
python manage.py migrate
15.orm增删改查
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 django.shortcuts import render,HttpResponse,redirect
def orm(request):
UserInfo.objects.create(name="test",password="123456",age=20)
UserInfo.objects.filter(id=1).delete()
UserInfo.objects.all().delete()
data_list=UserInfo.objects.all()
for obj in data_list:
print(obj.id,obj.name,obj.password,obj.age)
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,返回成功
|