目的:在Django新增模块-对数据库做读取、写入操作
- 创建 APP
Django规定,如果要使用模型,必须要创建一个app。我们使用以下命令创建一个 TestModel 的 app:
python manage.py startapp TestModel
得到的目录结构如下:
TestProject
|-- TestModel
| |-- migrations
| | |-- __init__.py
| |-- __init__.py
| |-- admin.py
| |-- models.py
| |-- tests.py
| | -- views.py
- 添加类
# models.py
from django.db import models
class Test(models.Model):
name = models.CharField(max_length=20)
以上的类名代表了数据库中的表名,且继承了models.Model,类里面的字段代表数据表中的字段(name),数据类型则由CharField(相当于varchar)、DateField(相当于datetime), max_length 参数限定长度。
接下来在settings.py中找到INSTALLED_APPS这一项,如下:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'TestModel',
]
- 将类生成数据库表
D:\pythonworkspace\TestProject>python manage.py makemigrations
Migrations for 'TestModel':
TestModel\migrations\0001_initial.py:
- Create model Test
D:\pythonworkspace\TestProject>python manage.py migrate
System check identified some issues:
WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, s
uch as data truncation upon insertion, by escalating warnings into errors. It is
strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.
10/ref/databases/#mysql-sql-mode
Operations to perform:
Apply all migrations: TestModel, admin, auth, contenttypes, sessions
Running migrations:
Applying TestModel.0001_initial... OK
数据库中新增了testmodel_test表,字段名为id,name
会在migrations中生成一个0001_initial.py文件
from __future__ import unicode_literals
from django.db import migrations, modelsclass Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Test',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20)),
],
),
]
- 写入数据库
testdb文件 写入数据
def add(request):
nameq = request.GET.get('q')
test1 = Test(name=nameq)
test1.save()
return HttpResponse("<p>add data ok</p>" + nameq)
页面
<form action="/addtest/" method="get">
<input type="text" name="q">
<input type="submit" value="Add">
</form>
url.py中
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^hello/$', hello),
url(r'^addtest/$', add),
url(r'^search/$', search),
url(r'^uptest/$', update),
url(r'^deltest/$', delete),
]
访问:http://localhost:8000/hello/
输入想添加的内容,点击 Add,往数据库中新增一条数据
- 读取数据库
testdb.py中查询方法
def search(request):
response = ""
response1 = ""
nameq = request.GET.get('q')
list = Test.objects.filter(name=nameq)
for var in list:
response1 += var.name + " "
response = response1
return HttpResponse("<p>" + response + "</p>")
页面
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
网友评论