search
HomeBackend DevelopmentPython TutorialDetailed explanation of Django's method of operating database based on ORM

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目录下
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',
  }
}

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

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

3. Configure the new app (blog and article)

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

4. Take blog as an example to 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的表。字段就是id和name

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'

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这个应用,名字要一致

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
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 ##生成同步计划,虽说改的是blog
python migrate article --database article ##执行计划,虽说改的是blog

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

vim view.py ##blog目录下,添加下列代码
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')
vim urls.py ##blog目录下
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), ##这里配置好
]
vim orm_handle_db.html ##blog/templates目录下

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目录下,添加下面两项
DATABASES_APPS_MAPPING = {
  'blog': 'default',
  'article': 'article',
    }
DATABASE_ROUTERS = ['HelloWorld.database_app_router.DatabaseAppsRouter']
vim database_app_router.py ##配置路由 ,HelloWorld/HelloWorld/目录下。直接粘贴
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

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目录下,添加下方代码
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')

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!

Statement
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
怎么将Django项目迁移到linux系统中怎么将Django项目迁移到linux系统中Jun 01, 2023 pm 01:07 PM

Django项目配置修改我们需要把原先的Django项目进行修改才能更好地进行项目迁移工作,首先需要修改的是settings.py文件。由于项目上线之后不能让用户看到后台的运行逻辑,所以我们要把DEBUG改成False,把ALLOWED_HOSTS写成‘*’,这样是为了允许从不同主机进行访问。由于linux中如果不加这句可能会出现文件找不到的情况,所以我们要把模板的路径进行拼接。由于做Django项目肯定进行过数据库的同步,所以我们要把migrations

centos+nginx+uwsgi部署django项目上线的方法centos+nginx+uwsgi部署django项目上线的方法May 15, 2023 am 08:13 AM

我django项目叫yunwei,主要app是rabc和web,整个项目放/opt/下如下:[root@test-codeopt]#lsdjango_virtnginxredisredis-6.2.6yunwei[root@test-codeopt]#lsyunwei/manage.pyrbacstatictemplatesuwsgiwebyunwei[root@test-codeopt]#lsyunwei/uwsgi/cut_log.shloguwsgi.iniuwsgi.loguwsgi.p

Django框架中的数据库迁移技巧Django框架中的数据库迁移技巧Jun 17, 2023 pm 01:10 PM

Django是一个使用Python语言编写的Web开发框架,其提供了许多方便的工具和模块来帮助开发人员快速地搭建网站和应用程序。其中最重要的一个特性就是数据库迁移功能,它可以帮助我们简单地管理数据库模式的变化。在本文中,我们将会介绍一些在Django中使用数据库迁移的技巧,包括如何开始一个新的数据库迁移、如何检测数据库迁移冲突、如何查看历史数据库迁移记录等等

Django框架中的文件上传技巧Django框架中的文件上传技巧Jun 18, 2023 am 08:24 AM

近年来,Web应用程序逐渐流行,而其中许多应用程序都需要文件上传功能。在Django框架中,实现上传文件功能并不困难,但是在实际开发中,我们还需要处理上传的文件,其他操作包括更改文件名、限制文件大小等问题。本文将分享一些Django框架中的文件上传技巧。一、配置文件上传项在Django项目中,要配置文件上传需要在settings.py文件中进

如何用nginx+uwsgi部署自己的django项目如何用nginx+uwsgi部署自己的django项目May 12, 2023 pm 10:10 PM

第一步:换源输入命令换掉Ubuntu的下载源sudonano/etc/apt/sources.list将以下全部替换掉原文件,我这里用的是阿里的源,你也可以换其他的。debhttp://mirrors.aliyun.com/ubuntu/bionicmainrestricteddebhttp://mirrors.aliyun.com/ubuntu/bionic-updatesmainrestricteddebhttp://mirrors.aliyun.com/ubuntu/bionicunive

使用Django构建RESTful API使用Django构建RESTful APIJun 17, 2023 pm 09:29 PM

Django是一个Web框架,可以轻松地构建RESTfulAPI。RESTfulAPI是一种基于Web的架构,可以通过HTTP协议访问。在这篇文章中,我们将介绍如何使用Django来构建RESTfulAPI,包括如何使用DjangoREST框架来简化开发过程。安装Django首先,我们需要在本地安装Django。可以使用pip来安装Django,具体

Django+Bootstrap构建响应式管理后台系统Django+Bootstrap构建响应式管理后台系统Jun 17, 2023 pm 05:27 PM

随着互联网技术的快速发展和企业业务的不断扩展,越来越多的企业需要建立自己的管理后台系统,以便于更好地管理业务和数据。而现在,使用Django框架和Bootstrap前端库构建响应式管理后台系统的趋势也越来越明显。本文将介绍如何利用Django和Bootstrap构建一个响应式的管理后台系统。Django是一种基于Python语言的Web框架,它提供了丰富的功

Django框架中的多数据库支持技巧Django框架中的多数据库支持技巧Jun 18, 2023 am 10:52 AM

Django是一款流行的Pythonweb框架,其出色的ORM(对象关系映射)机制让开发者能够轻松操作数据库。但是在一些实际项目中,需要连接多个数据库,这时候就需要一些技巧来保证项目的稳定性和开发效率。在Django中,多数据库的支持是基于Django框架自身提供的功能而实现的。在这里,我们将介绍一些多数据库支持的技巧,以帮助你在Django的开发中更好地

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!