Django model
Django provides a good variety of database support, including: PostgreSQL, MySQL, SQLite, Oracle.
Django provides a unified API calls for these databases. We can choose different database according to their business needs.
MySQL is the most commonly used Web application database. This chapter we will Mysql as an example are introduced. You can site MySQL tutorial to learn more Mysql basics.
Database Configuration
We find DATABASES configuration items in settings.py file for the project, its information will be revised as:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'test123', 'HOST':'localhost', 'PORT':'3306', } }
The above contains the database name, and user information, which corresponds to the same MySQL database and user settings. Django According to this setting, the MySQL database and the corresponding user connects.
Definition Model
Create APP
Django provides that if you want to use the model, we must create an app. We use the following command to create a TestModel the app:
python manage.py startapp TestModel
Directory structure is as follows:
HelloWorld |-- TestModel | |-- __init__.py | |-- admin.py | |-- models.py | |-- tests.py | `-- views.py
We modify TestModel / models.py file, as follows:
# models.py from django.db import models class Test(models.Model): name = models.CharField(max_length=20)
Above the class name represents a database table names, and inherited models.Model, class inside the field represents the data table fields (name), data type by CharField (equivalent to varchar), DateField (equivalent datetime), max_length parameters defined length.
Next, find INSTALLED_APPS this one in settings.py as follows:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'TestModel', # 添加此项 )
Run the command line python manage.py syncdb, see the word lines "Creating table ...", and your data table has been created.
Creating tables ... …… Creating table TestModel_test #我们自定义的表 ……
Composition table structure: app name _ the class name (eg: TestModel_test).
Note: Although we do not have the models set the primary key to the table, but Django automatically adds an id as the primary key.
Database Operations
Next we add testdb.py file HelloWorld directory and modify urls.py:
from django.conf.urls import * from HelloWorld.view import hello from HelloWorld.testdb import testdb urlpatterns = patterns("", ('^hello/$', hello), ('^testdb/$', testdb), )
Adding data
Adding data you need to create an object, and then perform the save function, the equivalent of the SQL INSERT:
# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # 数据库操作 def testdb(request): test1 = Test(name='w3cschool.cc') test1.save() return HttpResponse("<p>数据添加成功!</p>")
You can see the data access http://192.168.45.3:8000/testdb/ add a prompt success.
retrieve data
Django provides several ways to get the contents of the database, as shown in the following code:
# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # 数据库操作 def testdb(request): # 初始化 response = "" response1 = "" # 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM 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="w3cschool.cc").order_by("id") # 输出所有数据 for var in list: response1 += var.name + " " response = response1 return HttpResponse("<p>" + response + "</p>")
The output is shown below:
![](/django/testdb-get.jpg)
update data
You can modify the data using save () or update ():
# -*- 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 = 'w3cschool本教程' test1.save() # 另外一种方式 #Test.objects.filter(id=1).update(name='w3cschool本教程') # 修改所有的列 # Test.objects.all().update(name='w3cschool本教程') return HttpResponse("<p>修改成功</p>")
delete data
Deleted objects in the database simply call the object's delete () method:
# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # 数据库操作 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>")