In this paper, we introduce the Django-based ORM operation database method, combined with the example form summarizes the Django use ORM operation database related configuration, and other related operation skills, need friends can refer to, hope to help everyone.
1. Configuration database
Vim Settings #HelloWorld the/helloworld directory
DATABASES = {' default ': { ' ENGINE ': ' Django.db.backends.mysql ', #mysql数据库中第一个库test ' NAME ': ' Test ', ' USER ': ' Root ', ' PASSWORD ': ' 123456 ', ' HOST ': ' 127.0.0.1 ', ' PORT ': ' 3306 ', }, ' article ': { ' ENGINE ': ' Django.db.backends.mysql ', # Second library in MySQL database test2 ' NAME ': ' test2 ', ' USER ': ' Root ', ' PASSWORD ': ' 123456 ', ' HOST ': ' 127.0.0.1 ', ' PORT ': ' 3306 ', }}
2. Create a "web Site" (app) in the project directory
django-admin.py Startapp Blog # #HelloWorld/directory to build the website app, I built two apps (blog and article)
3. Configure the new app (blog and article)
Vim Settings ##/helloworld/helloworld Directory
Installed_apps = [ ' django.contrib.admin ', ' Django.contrib.auth ', ' django.contrib.contenttypes ', ' django.contrib.sessions ', ' django.contrib.messages ', ' django.contrib.staticfiles ', ' blog ', ' article ',]
4, take the blog as an example, create a model
Vim models.py # #blog目录下
From django.db import models# Create your models Here.class Teacher (models. Model): id = models. Integerfield (primary_key=true) name = models. Charfield (max_length=50) class Meta: db_table = ' teacher ' #默认库test中建立名为teacher的表. field is ID and name
5. Synchronizing the model into the database
Python manage.py Migrate # #建立Django系统表, First run
Python manage.py makemigrations # #生成迁移计划, run a build schedule every time you add a table or field
Python manage.py Migrate # #同步用户定义的表
Vim models.py #blog目录下, new table test, you can add or modify the deletion of a few fields to try
Class Student (models. Model): id = models. Integerfield (primary_key=true) name = models. Charfield (max_length=50) Student_number = models. Charfield (default= "", max_length=50) class Meta: db_table = ' student '
6, the use of multiple databases , the top of the blog application database in the test library, and then build an application article with Test2 this library. The two applications in such a project are in separate libraries.
I have created the article app above and configured the databases in settings.py to be test2 in the corresponding database. Note that the name of article should be consistent.
CD article #进入article目录
Vim models.py #article目录下
From django.db import Modelsclass Author (models. Model): id = models. Integerfield (primary_key=true) name = models. Charfield (max_length=50) Author_ids = models. Charfield (MAX_LENGTH=50) class Meta: db_table = ' author ' App_label = ' article ' # #对应的article这个应用, name consistent
Python manage.py makemigrations article # #生成同步计划
# #对article应用执行同步, sync to article (configuration in Settings, corresponding to test2) in the corresponding database.
Python migrate article--database article # #执行计划, you must add--database to specify the libraries to synchronize
7, the 6th step multiple applications use their own database has been configured, but there is an application using multiple databases, this step is configured.
CD blog #进入blog目录下vim models.py # #blog目录下, add a table to the file, note the back App_label
Class Group (models. Model): id = models. Integerfield (primary_key=true) group_name = models. Charfield (max_length=50) class Meta: db_table = ' group ' App_label = ' article ' # #必须指定这个库
Python manage.py makemigrations article # #生成同步计划, although the change is Blogpython migrate article--database article # #执行计划, although the change is blog
8, start the operation of database testing , blog as an example:
Vim view.py # #blog目录下, add the following code
From blog.models import teacherdef orm_handle_db (Request): test1 = Teacher (id=1,name= ' Runoob ', teacher_number= ' # #定义数据 Test1.save () # #保存 return render_to_response (' orm_handle_db.html ')
Vim urls.py # #blog目录下
From django.conf.urls Import Urlfrom Blog Import viewsurlpatterns = [ url (R ' ^hello/$ ', Views.hello), url (r ' ^ search/$ ', views.search), url (r ' ^post_search/$ ', views.post_search), url (r ' ^search_submit$ ', Views.search _submit), url (r ' ^post_search_submit$ ', views.post_search_submit), url (r ' ^db_handle/$ ', Views.db_handle), URL (r ' ^orm_handle_db/$ ', views.orm_handle_db), # #这里配置好]
Vim orm_handle_db.html # #blog/templates Directory
Database operations
Other operations: Adding and deleting changes and sorting the group operation of their own query can be, the image below reference
9. Operation of another database test2 how to do it?
Vim settings.py # #HelloWorld The/helloworld directory, add the following two items
databases_apps_mapping = { ' blog ': ' Default ', ' article ': ' article ', }database_routers = [' Helloworld.database_app_router. Databaseappsrouter ']
Vim database_app_router.py # #配置路由, helloworld/helloworld/directory. Paste directly
from django.conf import Settingsclass databaseappsrouter (object):d EF db_for_ Read (self, model, **hints): App_label = Model._meta.app_labelif App_label in Settings. Databases_apps_mapping:res = settings. Databases_apps_mapping[app_label]print (RES) return Resreturn nonedef db_for_write (self, model, **hints): App_label = Model._meta.app_labelif App_label in Settings. Databases_apps_mapping:return settings. Databases_apps_mapping[app_label]return nonedef allow_relation (self, obj1, obj2, **hints):d b_obj1 = settings. Databases_apps_mapping.get (obj1._mata.app_label) db_obj2 = settings. Databases_apps_mapping.get (Obj2._mata.app_label) if db_obj1 and db_obj2:if db_obj1 = = Db_obj2:return Trueelse:return Falsereturn nonedef db_for_migrate (self, DB, App_label, Model_name=none, **hints): If DB in Settings. Databases_apps_mapping.values (): Return settings. Databases_apps_mapping.get (App_label) = = Dbelif App_label in Settings. Databases_apps_mapping:return Falsereturn None
Then, as the 8th step, the database will be automatically routed to the appropriate database.
Vim views.py #blog目录下, add the code below
From blog.models import teacher,group# #这是第8步没有的def orm_handle_db (Request): test1 = Teacher (id=1,name= ' Runoob ', Teacher_number= ') test2 = Group (id=1,group_name= ' Runoob ') # #这是第8步没有的 test1.save () Test2.save () # # This is the 8th step without the return render_to_response (' orm_handle_db.html ')
10. For table link operations in a single library (1-to-1, many-to-1, many-to-many). See video if necessary. I really don't want to use a foreign key.
11, the table link operation Django is not supported, you need to use bypass ORM to operate the way. See summary document
Summary: simple operation with ORM, complex operation with bypass ORM mode.