django连接数据库与orm基础知识


一、django连接数据库

django自带的sqlite3是一个小型的数据库 功能比较少 主要用于本地测试
我们实际项目中都会替换掉它

默认配置sqlite3

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

我们在学习过程中使用mysqlclient模块替换默认的数据库

1.需要指定模块

	django1.X版本需要在项目目录下或者app目录下的__init__.py编写代码
    	import pymysql
    	pymysql.install_as_MySQLdb()
	django2.X及以上都可以直接通过下载mysqlclient模块解决
    	pip3.8 install mysqlclient
        或是pycharm中下载

image

ps:该模块windows下载问题不大 主要是mac电脑可能有问题

2.修改配置文件

DATABASES = {
    'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'day51',
            'HOST': '127.0.0.1',
            'PORT': 3306,
            'USER': 'root',
            'PASSWORD': '123',
            'CHARSET': 'utf8'
        }
}

app文件目录中的双下init文件也需要添加配置

import pymysql
pymysql.install_as_MySQLdb()

image

二、pycharm连接MySQL数据库

方式一:

在pycharm右上角点击图标后创建连接

image

之后弹出一个弹窗,输入数据库的信息

image

第一次连接的时候会要求下载插件,这里点击下载就好了,很快的

image

接着点击下方的Test Connection测试连接,成功了就可以点击ok保存退出了

image

方式二:

使用左下角的图标连接数据库

image
后续操作参考方法一

三、ORM简介

1、ORM概念

对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。

简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。因此实现了让不会SQL语句的python程序员,使用python面向对象的语法来操作数据库的目的。

ORM在业务逻辑层和数据库层之间充当了桥梁的作用。

类				    表
对象				   一条条数据
对象点名字			 数据获取字段对应的值

ps:ORM由于高度封装了SQL,所以有时候效率较低,我们需要自己写SQL。

2、ORM由来

让我们从O/R开始。字母O起源于"对象"(Object),而R则来自于"关系"(Relational)。

几乎所有的软件开发过程中都会涉及到对象和关系数据库。在用户层面和业务逻辑层面,我们是面向对象的。当对象的信息发生变化的时候,我们就需要把对象的信息保存在关系数据库中。

按照之前的方式来进行开发就会出现程序员会在自己的业务逻辑代码中夹杂很多SQL语句用来增加、读取、修改、删除相关数据,而这些代码通常都是重复的。

3、ORM的优势和劣势

ORM的优势

ORM解决的主要问题是对象和关系的映射。它通常把一个类和一个表一一对应,类的每个实例对应表中的一条记录,类的每个属性对应表中的每个字段。

ORM提供了对数据库的映射,不用直接编写SQL代码,只需像操作对象一样从数据库操作数据。

让软件开发人员专注于业务逻辑的处理,提高了开发效率。

ORM的劣势

ORM的缺点是会在一定程度上牺牲程序的执行效率。

ORM用多了SQL语句就不会写了,关系数据库相关技能退化…

四、ORM基本操作

因为ORM相当于是对数据库进行映射操作,所以我们需要跟数据库中的表建立关系

1.现在app中的models.py中编写模型类

	class GirlsInfo(models.Model):
        # 字段名 = 字段类型 + 约束条件
        id = models.AutoField(primary_key=True)  
        name = models.CharField(max_length=32)
        age = models.IntegerField()

2.执行数据库迁移相关命令

	python38 manage.py makemigrations  将操作记录到小本本上(migrations)
    执行成功后migrations文件夹下会多出一个py文件
	python38 manage.py migrate		  将操作同步到数据库上
'''注意每次在models.py修改了与数据库相关的代码 都需要再次执行上述命令'''

如果出现下方问题

image

解决方案是修改配置文件

image

成功的结果如下图

image

image

image

五、ORM基本语句

from app01 import models
models.类名.objects.create()		创建记录
models.UserInfor.objects.create(name='zzh',pwd='123')

models.类名.objects.filter()		查看记录
res = models.UserInfor.objects.filter(name=name)
print(res)
print(res[0])
print(res[0].id)
print(res[0].name)
print(res[0].pwd)

models.类名.objects.update()		修改记录
models.UserInfor.objects.filter(id=2).update(name='xiaozhu',pwd='666')

models.类名.objects.delete()		删除记录
models.UserInfor.objects.filter(id=2).delete()

六、用orm实现可视化界面之数据增删改查

小知识点:

  • 针对数据对象主键字段的获取可以使用更加方便的 obj.pk获取
  • 在模型类中定义双下str方法可以在数据对象被执行打印操作的时候方便的查看
  • form表单中能够触发提交动作的按钮只有两个
<input type='submit'/>
<button></button>

数据增删改查功能

1.数据展示功能
开设接口、获取数据、传递页面、展示数据

view.py

def user_list_func(request):
    user_data = models.UserInfor.objects.filter()
    return render(request,'userListPage.html',{'user_data':user_data})

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List</title>
    {% load static %}
    <script src="{% static 'jquery-3.6.1.js' %}"></script>
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 class="text-center">数据展示页</h1>
            <div class="col-md-8 col-md-offset-2">
                <a href="/user_add/" class="btn btn-success">数据添加</a>
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th>Pwd</th>
                            <th class="text-center">Operation</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for user_obj in user_data %}
                            <tr>
                                <td>{{ user_obj.pk }}</td>
                                <td>{{ user_obj.name }}</td>
                                <td>{{ user_obj.pwd }}</td>
                                <td class="text-center">
                                    <a href="/user_edit/?edit_id={{ user_obj.pk }}" class="btn btn-primary btn-xs">编辑</a>
                                    <a href="/user_delete/?delete_id={{ user_obj.pk }}" class="btn btn-danger btn-xs delBtn">删除</a>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        $('.delBtn').click(function (){
            let res = confirm('确定删除吗')
            if (res){

            }else {
                return false
            }
        })
    </script>
</body>
</html>

2.数据添加功能
开设接口、获取数据、发送数据、校验数据、录入数据、重定向

view.py

def user_add_func(request):
    if request.method == 'POST':
        name_infor = request.POST.get('name')
        pwd_infor = request.POST.get('pwd')
        if len(name_infor) == 0 or len(pwd_infor) == 0:
            return HttpResponse('用户名或年龄不能为空')
        user_infor = models.UserInfor.objects.filter(name=name_infor)
        if user_infor:
            return HttpResponse('用户名已存在')
        models.UserInfor.objects.create(name=name_infor, pwd=pwd_infor)
        return redirect('/user_list/')
    return render(request, 'userAddPage.html')

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add</title>
    {% load static %}
    <script src="{% static 'jquery-3.6.1.js' %}"></script>
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.css' %}">
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 class="text-center">数据添加页</h1>
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p>name:
                        <input type="text" name="name" class="form-control">
                    </p>
                    <p>pwd:
                        <input type="text" name="pwd" class="form-control">
                    </p>
                    <input type="submit" value="添加用户" class="btn btn-warning btn-block">
                </form>
            </div>
        </div>
    </div>

</body>
</html>

3.数据编辑功能
开设接口、后端如何区分所要编辑的数据(问号携带参数)、后端获取用户数据、前端展示默认数据、获取用户并完成更新

view.py

def user_edit_func(request):
    target_edit_id = request.GET.get('edit_id')
    if request.method == 'POST':
        name_infor = request.POST.get('name')
        pwd_infor = request.POST.get('pwd')
        if len(name_infor) == 0 or len(pwd_infor) == 0:
            return HttpResponse('用户名或年龄不能为空')
        models.UserInfor.objects.filter(pk=target_edit_id).update(name=name_infor, pwd=pwd_infor)
        return redirect('/user_list/')

    target_edit_obj = models.UserInfor.objects.filter(pk=target_edit_id)[0]
    print(target_edit_obj)
    return render(request, 'userEditPage.html', {'target_edit_obj': target_edit_obj})

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>edit</title>
    {% load static %}
    <script src="{% static 'jquery-3.6.1.js' %}"></script>
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.css' %}">
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 class="text-center">数据编辑页</h1>
            <div>
                <form action="" method="post">
                    <p>name:
                        <input type="text" name="name" class="form-control" value="{{ target_edit_obj.name }}">
                    </p>
                    <p>pwd:
                        <input type="text" name="pwd" class="form-control" value="{{ target_edit_obj.pwd }}">
                    </p>
                    <input type="submit" value="编辑用户" class="btn btn-primary btn-block">
                </form>
            </div>

        </div>
    </div>
</body>
</html>

4.数据删除功能
开设接口、问号携带参数、删除二次确认

view.py

def user_delete_func(request):
    target_delete_id = request.GET.get('delete_id')
    models.UserInfor.objects.filter(pk=target_delete_id).delete()
    return redirect('/user_list/')


posted @   致丶幻  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
  1. 1 So Far Away (Acoustic) Adam Christopher
  2. 2 雪 Distance Capper&罗言RollFlash
  3. 3 CollapsingWorld
  4. 4 Call You Tonight Johnta Austin
So Far Away (Acoustic) - Adam Christopher
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作曲 : David Guetta/Giorgio H Tuinfort/Jamie Scott/Martijn G Garritsen

Light ‘em up, light ‘em up

Tell me where you are, tell me where you are

The summer nights, the bright lights

And the shooting stars, they break my heart

I‘m calling you now, but you‘re not picking up

Your shadows so close if you are still in love

Then light a match, light a match

Baby, in the dark, show me where you are

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day and now you‘re so far away

It‘s breaking me, I‘m losing you

We were far from perfect, but we were worth it

Too many fights, and we cried, but never said we‘re sorry

Stop saying you love me

You‘re calling me now, but I can‘t pick up

Your shadow‘s too close, and I‘m still in love

The summer‘s over now, but somehow, it still breaks my heart

We could have had the stars, oh

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day and now you‘re so far away

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day when you‘re so far away

点击右上角即可分享
微信分享提示