本文将抽象的东西尽可能的可视化,目的是让基础不太好的同学理解的更清晰。本系列Django教程大多来自菜鸟教程,加入了一些个人理解和可视化部分。
工具:MySQL Workbench 6.1.7 CE
pycharm
数据库配置:
setting.py下DATABASES
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'root',
'PASSWORD':'***',
'HOST':'127.0.0.1',
'PORT':'3306',
}}`
修改models.py文件
# models.py
from django.db import models
class Test(models.Model):
name = models.CharField(max_length=20)```
以上的类名代表了数据库表名,如app名为blog,则此表名为*blog_test*,且继承了models.Model,类里面的字段代表数据表中的字段(name),数据类型则由CharField(相当于varchar)、DateField(相当于datetime), max_length 参数限定长度。
- 在命令行中运行,或者在pycharm编程的可以直接点击下方*Terminal*:
`$ python manage.py migrate # 创建表结构`
`$ python manage.py makemigrations yourapp.name # 让 Django 知道我们在我们的模型有一些变更`

`$ python manage.py migrate yourapp.name # 创建表结构`

数据库里看了一下出现了这么多表

## 数据库操作
接下来我们添加 testdb.py 文件,并修改 urls.py:
```javascript
from . import testdb
urlpatterns = {
url(r'^testdb$', testdb.testdb),
}```
- **添加数据**
数据需要先创建对象,然后再执行 save 函数,相当于SQL中的INSERT:
```javascript
#testdb.py
def testdb(request):
test1 = Test(name = 'vonhehe')
test1.save()
return HttpResponse("<p>数据添加成功</p>")```
我们运行一下看看:

再到数据库看看,数据添加到了blog_test表中

- **获取数据**
```javascript
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Test
def testdb(request):# 数据库操作
#初始化
response = ""
response1 = ""
# 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM blog_test
list = Test.objects.all()
# filter相当于SQL中的WHERE,可设置条件过滤结果
response2 = Test.objects.filter(id=1)
# 获取单个对象
response3 = Test.objects.get(id=1)
# 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
Test.objects.order_by('name')[0:2]
#数据排序
Test.objects.order_by("id")
# 上面的方法可以连锁使用
Test.objects.filter(name="vonhehe").order_by("id")
# 输出所有数据
for var in list:
response1 += var.name + " </br>"
response = response1
return HttpResponse("<p>" + response + "</p>")```
运行结果如下:

- **更新数据**
修改数据可以使用 save() 或 update():
```javascript
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Test
# 数据库更新操作
def testdb(request):
# 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE
test1 = Test.objects.get(id=1)
test1.name = 'Google'
test1.save()
# 另外一种方式
#Test.objects.filter(id=1).update(name='Google')
# 修改所有的列
# Test.objects.all().update(name='Google')
return HttpResponse("<h1>修改成功</h1>")```
运行结果如下:

在数据库中:

- **删除数据**
我们先添加一个数据:
`Test(name = 'vonhehe').save()`

```javascript
# 数据库删除操作
def testdb(request):
# 删除id=1的数据
test1 = Test.objects.get(id=1)
test1.delete()
# 另外一种方式
# Test.objects.filter(id=1).delete()
# 删除所有数据
# Test.objects.all().delete()
return HttpResponse("<p>删除成功</p>")```
运行结果如下:

数据库如下,id=1行已被删除:

***
---本文参考[【菜鸟教程】](http://www.runoob.com/django/django-model.html)