0%

教程3 Django操作Mysql(删除、修改数据)

Django框架,以MVT(mvc+T)模式高效开发web,超越spring系列的存在

Django操作Mysql(删除、修改数据)

一.前期工作

  • 生成app

命令行输入

1
>python manage.py startapp webname
  • 配置setting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#数据库
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdata2',
'USER': 'root',
'PASSWORD': '121212', #数据库密码
'HOST': '127.0.0.1',
'PORT': '3306'
}
}

#注册app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'web',
]

  • 配置__init__.py
1
2
3
# 先安装pymysql包
import pymysql
pymysql.install_as_MySQLdb()

二.MVC配置

  • model层(models.py)

    建几个类就对应几张表

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    from django.db import models

    # Create your models here.
    class Classes(models.Model):
    titile = models.CharField(max_length=32)
    m = models.ManyToManyField("Teachers")

    class Teachers(models.Model):
    name = models.CharField (max_length=32)

    class Student(models.Model):
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.BooleanField()
    cs = models.ForeignKey(Classes,on_delete=models.CASCADE,)
  • views层(views.py)

    先把views.py删除,用一个文件夹views替代,在文件夹下建立classes.py、students.py、teachers.py三个文件,分别代表三个视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#其中classes.py如下:
from django.shortcuts import render
from django.shortcuts import redirect
from web import models


def get_classes(request):
cls_list = models.Classes.objects.all()
return render(request, 'get_classes.html', {'cls_list': cls_list})


def add_classes(request):
if request.method == "GET":
return render(request, 'add_classes.html')
elif request.method == 'POST':
title = request.POST.get('titile')
models.Classes.objects.create(titile=title)
return redirect('/get_classes.html')


def del_classes(request):
nid = request.GET.get('nid')
models.Classes.objects.filter(id=nid).delete()
return redirect('/get_classes.html')


def edit_classes(request):
if request.method == 'GET':
nid = request.GET.get('nid')
obj = models.Classes.objects.filter(id=nid).first()
return render(request, 'edit_classes.html', {'obj': obj})
elif request.method == 'POST':
nid = request.GET.get('nid')
title = request.POST.get('title')
models.Classes.objects.filter(id=nid).update(titile=title)
return redirect('/get_classes.html')
  • control层(urls.py文件)
1
2
3
4
5
6
7
8
9
10
11
12
13
from django.conf.urls import url
from django.contrib import admin
from web.views import classes

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^get_classes.html$', classes.get_classes),
url(r'^add_classes.html$', classes.add_classes),
url(r'^del_classes.html$', classes.del_classes),
url(r'^edit_classes.html$', classes.edit_classes),
url(r'',classes.get_classes),#首页默认页面
]

三、模版层(templates)

先创建templates文件夹,在settings.py设置templates文件夹路径(参考上一讲)

  • get_classes.html
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <div>
    <a href="/add_classes.html">添加</a>
    </div>
    <div>
    <table border="1">
    <thead>
    <tr>
    <th>ID</th>
    <th>名称</th>
    <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {% for row in cls_list %}
    <tr>
    <td>{{ row.id }}</td>
    <td>{{ row.titile }}</td>
    <td>
    <a href="/del_classes.html?nid={{ row.id }}">删除</a>
    |
    <a href="/edit_classes.html?nid={{ row.id }}">编辑</a>
    </td>
    </tr>
    {% endfor %}
    </tbody>
    </table>
    </div>
    </body>
    </html>
  • add_classes.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="add_classes.html" method="POST">
{% csrf_token %}
<input type="text" name="titile" />
<input type="submit" value="提交" />
</form>
</body>
</html>
  • edit_classes.html
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<form action="/edit_classes.html?nid={{ obj.id }}" method="POST">
{% csrf_token %}
<input type="text" name="title" value="{{ obj.titile }}" />
<input type="submit" value="提交"/>
</form>
</body>
</html>

四、其他

  • 同步到数据库操作

    命令行两步操作

1
2
3
>python manage.py makemigrate webname #输出modles到数据库到中间文件

>python namge.py migrate #同步到数据库
  • 中文设置

    Django和Mysql本身默认数据库编码不能识别中文数据,需将设置

    1.setting.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdata3',
'USER': 'root',
'PASSWORD': '121212', #数据库密码
'HOST': '127.0.0.1',
'PORT': '3306',
'CHARSET':'utf8',
'COLLATION':'utf8_general_ci',
}
}

//增加CHARSET字段
//增加增加COLLATION字段

image

2. mysql设置

通过设置设置编码utf-8支持中文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>show create database xxx
//查看xxx数据库编码

>show create table xxx
//查看表xxx编码

>alter table table_name convert to character set utf8;
//更改表编码

>create database xxx character set utf8
//创建数据库xxx时设定编码

>alter database xxx character set utf8;
//修改数据库xxx时设定编码

>insert into xxx values ("小明");
//测试中文

参考

https://www.cnblogs.com/nulige/p/6529175.html