Home > Backend Development > Python Tutorial > Detailed explanation of Django's method of operating database based on ORM

Detailed explanation of Django's method of operating database based on ORM

小云云
Release: 2018-05-18 14:14:48
Original
2702 people have browsed it

This article mainly introduces Django's method of operating the database based on ORM. It summarizes and analyzes the related configuration, addition, deletion, modification and query of Django's use of ORM to operate the database in the form of examples. Friends who need it can refer to it. I hope it can help. to everyone.

1. Configure the database

vim settings #HelloWorld/HelloWorld目录下
Copy after login
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', # mysql数据库中第二个库test2
    'NAME': 'test2',
    'USER': 'root',
    'PASSWORD': '123456',
    'HOST':'127.0.0.1',
    'PORT':'3306',
  }
}
Copy after login

2. Create a "web site" (app) in the project directory

django-admin.py startapp blog ##HelloWorld/目录下建立网站app,我建了两个app(blog和article)
Copy after login

3. Configure the new app (blog and article)

vim settings ##/HelloWorld/HelloWorld目录下
Copy after login
INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'blog',
  'article',
]
Copy after login

4. Take blog as an example to create a model

vim models.py ##blog目录下
Copy after login
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的表。字段就是id和name
Copy after login

5. Synchronize the model to the database

python manage.py migrate ##Create the Django system table and run it for the first time
python manage.py makemigrations ## Generate a migration plan, and run the generated plan every time you add a table or field
python manage.py migrate ##Synchronize user-defined tables

vim models.py #In the blog directory, create a new table for testing , you can try adding or modifying or deleting a few fields

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'
Copy after login

6. Use of multiple databases, the blog application above corresponds to the test library in the database, and then build an application article for use test2 library. The two applications in such a project use different libraries.

I have created the article application above, and configured the corresponding database in the DATABASES item in settings.py to be test2. Note that the name article must be consistent.

cd article #Enter the article directory
vim models.py #Under the article directory

from django.db import models
class 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这个应用,名字要一致
Copy after login

python manage.py makemigrations article ##Generate synchronization plan
##Execute the article application Synchronize to the database corresponding to article (configuration in settings, corresponding to test2).
python migrate article --database article ##Execution plan, you must add --database to specify the library to be synchronized

7. Step 6: Multiple applications have been configured to use their own databases, but there is a situation where one application uses multiple databases. Configure this step.

cd blog #进入blog目录下
vim models.py ##blog目录下,在文件中增加一个表,注意后边app_label
Copy after login
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' ##必须指定这个库
Copy after login
python manage.py makemigrations article ##生成同步计划,虽说改的是blog
python migrate article --database article ##执行计划,虽说改的是blog
Copy after login

8. Start operating the database test, take blog as an example:

vim view.py ##blog目录下,添加下列代码
Copy after login
from blog.models import Teacher
def orm_handle_db(request):
  test1 = Teacher(id=1,name='runoob',teacher_number='10') ##定义数据
  test1.save() ##保存
  return render_to_response('orm_handle_db.html')
Copy after login
vim urls.py ##blog目录下
Copy after login
from django.conf.urls import url
from blog import views
urlpatterns = [
  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), ##这里配置好
]
Copy after login
vim orm_handle_db.html ##blog/templates目录下
Copy after login

Database operation

Others Operation: Add, delete, modify, search, sort and group operations can be queried by yourself. Refer to the image below

9. How to operate another database test2

vim settings.py ##HelloWorld/HelloWorld目录下,添加下面两项
Copy after login
DATABASES_APPS_MAPPING = {
  'blog': 'default',
  'article': 'article',
    }
DATABASE_ROUTERS = ['HelloWorld.database_app_router.DatabaseAppsRouter']
Copy after login
vim database_app_router.py ##配置路由 ,HelloWorld/HelloWorld/目录下。直接粘贴
Copy after login
from django.conf import settings
class DatabaseAppsRouter(object):
def db_for_read(self, model, **hints):
app_label = model._meta.app_label
if app_label in settings.DATABASES_APPS_MAPPING:
res = settings.DATABASES_APPS_MAPPING[app_label]
print(res)
return res
return None
def db_for_write(self, model, **hints):
app_label = model._meta.app_label
if app_label in settings.DATABASES_APPS_MAPPING:
return settings.DATABASES_APPS_MAPPING[app_label]
return None
def allow_relation(self, obj1, obj2, **hints):
db_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 True
else:
return False
return None
def 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) == db
elif app_label in settings.DATABASES_APPS_MAPPING:
return False
return None
Copy after login

After that, just operate the database as in step 8. The corresponding database will be automatically routed to find the corresponding database

vim views.py #blog目录下,添加下方代码
Copy after login
from blog.models import Teacher,Group##这是第8步没有的
def orm_handle_db(request):
  test1 = Teacher(id=1,name='runoob',teacher_number='10')
  test2 = Group(id=1,group_name='runoob') ##这是第8步没有的
  test1.save()
  test2.save()##这是第8步没有的
  return render_to_response('orm_handle_db.html')
Copy after login

10. For table link operations in a single library (1 to 1, many to 1, many-to-many). See the video if necessary. I really don’t want to use the foreign key method

11. Django does not support Kwaku’s table link operation, so you need to use a method that bypasses the ORM. See the summary document

Summary: Use ORM for simple operations, and bypass the ORM for complex operations.

The above is the detailed content of Detailed explanation of Django's method of operating database based on ORM. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template