Django-ORM框架

一、ORM简介

到目前为止,当程序涉及到数据库相关操作时, 我们一般会这样搞:

  • 创建数据库,设计表结构和字段
  • 使用pymysql来连接数据库,并编写数据访问层代码
  • 业务逻辑层去调用数据访问层执行数据库操作
'''
ORM: Object Relational Mapping  对象关系映射
    类名对应————————>>> 数据库中的表名
    类属性对应————————>>> 数据库中的字段
    类实例对应————————>>> 数据库表中的一行数据
    obj.id  obj.name........ 类实例对象的属性
'''

二、配置ORM

  • 在settings.py里配置数据库连接信息
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'fred_li',
        'PASSWORD': '835y1354',
        'NAME': 'game',
        'OPTIONS': {
            'init_command': 'SET sql_mode=STRICT_TRANS_TABLES',  # 开启mysql严格模式
            # Strict Mode功能说明
              # 不支持对not null字段插入null值
              # 不支持对自增长字段插入”值
              # 不支持text字段有默认值
        }
    }
}
  • 在app目录下的__init__.py里设置Django默认连接mysql的方式
import pymysql
pymysql.install_as_MySQLdb()

三、数据库迁移

1.在models.py里创建表

from django.db import models


# Create your models here.

class User(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

2.进行数据库迁移

2.1 terminal下执行 python3 manage.py makemigrations  生成数据库执行脚本

# Generated by Django 2.0 on 2019-03-11 07:34

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=32)),
                ('pwd', models.CharField(max_length=32)),
            ],
        ),
    ]
app01/migrations/0001_initial.py

2.2 terminal下执行 python3 manage.py migrate 将2.1生成的数据库脚本导入到数据库中

首次迁移会Django会创建其所需的其他基础表

D:codemylogin>python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying app01.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

注意: ORM不能创建数据库,需要手动创建,如果没有,则migrate时会报错

四、ORM的简单使用(查询)

from django.shortcuts import render, HttpResponse,redirect
import pymysql
from app01 import models   # 导入model

# Create your views here.

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        # 取出POST中携带的参数
        name=request.POST.get('name')
        pwd=request.POST.get('pwd')
        if name and pwd:
            # 去数据库里查
            user=models.User.objects.filter(name=name,pwd=pwd).first()
            print(type(user))
            # print(user.name,user.pwd)  # user是一个实例对象  对象.属性 可获取到属性的值
            if user:    # user有值的情况
                return redirect('https://www.baidu.com')
            else:
                return HttpResponse('用户名或密码错误')
        else:
            return HttpResponse('用户名或密码不能为空')
原文地址:https://www.cnblogs.com/lichunke/p/10511139.html