django之ORM介绍
ORM
在进入ORM之前,先看一下传统的操作数据库的方式:
import pymysql db = pymysql.connect(db= "guest", user="root", passwd="", host="127.0.0.1",) cursor = db.cursor() cursor.execute("select realname from sign_guest order by create_time") name = [row[0] for row in cursor.fetchall()] print(name) [‘张三‘, ‘李四‘, ‘康‘, ‘李五‘, ‘lily‘, ‘zhangailing‘, ‘dulala‘, ‘adu‘, ‘tester01‘, ‘tester01‘, ‘tester02‘, ‘andy‘, ‘vivian‘] 2~5 ---- 首先要连接db 6 ---- 然后获得db的执行器对象 7 ---- 然后通过执行器运行sql,此时cursor对象相当于一个容器,存放了执行sql的结果 8 ---- 最后从cursor中取出来数据
是不是很费事?那么ORM到底是什么呢? ORM就是可以把对db的增删改查等一系列操作通过class.method或者class.attribute的方式来操作,是不是很简单,那么看一下下面这个demo,这个demo就是设计并创建了表,可以先看一下代码demo:
from django.db import models # Create your models here. class UserMessage(models.Model): # UserMessage对应db的表名 name = models.CharField(max_length=20, verbose_name="用户名") email = models.EmailField(verbose_name="邮箱") address = models.CharField(max_length=100, verbose_name="联系地址") message = models.CharField(max_length=500, verbose_name="留言信息") class Meta: verbose_name = "用户留言信息"
开始演示---------
先贴出来demo的目录结构
首先在message这个应用下的models.py编写一个model代码
from django.db import models # Create your models here. class UserMessage(models.Model): # UserMessage对应db的表名 name = models.CharField(max_length=20, verbose_name="用户名") email = models.EmailField(verbose_name="邮箱") address = models.CharField(max_length=100, verbose_name="联系地址") message = models.CharField(max_length=500, verbose_name="留言信息") class Meta: verbose_name = "用户留言信息"
这里在项目目录执行makemigrations命令,创建model
D:\myproject\djangopro1 (venv3) $ python manage.py makemigrations message System check identified some issues: WARNINGS: ?: (2_0.W001) Your URL pattern ‘^form/$‘ has a route that contains ‘(?P<‘, begins with a ‘^‘, or ends with a ‘$‘. This was likely an oversight when migrating to django.urls.path(). Migrations for ‘message‘: message\migrations\0001_initial.py - Create model UserMessage
注意:message在django工程里是一个应用的角色,要注册到djangopro1工程的djangopro1里的settings.py中(图中的2,暂时理解为工程主配置应用)
命令执行如果没有报错,继续执行migrate,如下:
D:\myproject\djangopro1 (venv3) $ python manage.py migrate message System check identified some issues: WARNINGS: ?: (2_0.W001) Your URL pattern ‘^form/$‘ has a route that contains ‘(?P<‘, begins with a ‘^‘, or ends with a ‘$‘. This was likely an oversight when migrating to django.urls.path(). Operations to perform: Apply all migrations: message Running migrations: Applying message.0001_initial... OK
到这里UserMessage表就创建成功了,可以在db看一下表结构