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

The example in this article describes how Django operates a database based on ORM. Share for your reference, the details are as follows:

1. Configure the database

vim settings #HelloWorld/HelloWorld directory
DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql', #The first library test in the mysql database
    'NAME': 'test',
    'USER': 'root',
    'PASSWORD': '123456',
    'HOST':'127.0.0.1',
    'PORT':'3306',
  },
  'article': {
    'ENGINE': 'django.db.backends.mysql', # The second library test2 in the mysql database
    '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/ Create a website app in the directory, I built two apps (blog and article)

Django, ORM, database

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 blog as an example to create a model

vim models.py ##blog directory
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'#A table named teacher is created in the default library test. Fields are id and name

5. Synchronize the model to the database

python manage.py migrate ##Create Django system table, you can run it for the first time
python manage.py makemigrations ##Generate a migration plan, run the build plan every time a table or field is added
python manage.py migrate ##Sync user-defined tables
vim models.py #blog directory, create a new table to test, you can try adding or modifying and deleting several 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. For the use of multiple databases , the blog application above corresponds to the test library in the database, and then build an application article using the 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 of article should be consistent.

cd article #Enter the article directory
vim models.py #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' ##The corresponding article application, the name should be the same
python manage.py makemigrations article ##Generate synchronization plan
##Execute synchronization on the article application and synchronize to the database corresponding to the 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. In step 6, multiple applications using their own databases have been configured, but there is a situation where one application uses multiple databases. This step is configured.

cd blog #Enter the blog directory
vim models.py ##blog directory, add a table to the file, pay attention to the app_label behind
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' ##Must specify this library
python manage.py makemigrations article ##Generate synchronization plan, although the change is blog
python migrate article --database article ##Execution plan, although the blog is changed

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

See website: http://www.runoob.com/django/django-model.html

vim view.py ##blog directory, add the following code
from blog.models import Teacher
def orm_handle_db(request):
  test1 = Teacher(id=1,name='runoob',teacher_number='10') ##Define data
  test1.save () ## Save
  return render_to_response('orm_handle_db.html')
vim urls.py ##blog directory
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), ##Configured here
]
vim orm_handle_db.html ##blog/templates directory

database operations

Other operations: Add, delete, modify, search and sort and group operations to query by yourself

9. How to operate another database test2

vim settings.py ##HelloWorld/HelloWorld directory, add the following two
DATABASES_APPS_MAPPING = {
  'blog': 'default',
  'item': 'item',
    }
DATABASE_ROUTERS = ['HelloWorld.database_app_router.DatabaseAppsRouter']
vim database_app_router.py ##Configure routing, in the HelloWorld/HelloWorld/ directory. Paste directly
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

Then operate the database like step 8, and it will automatically find the corresponding database.

vim views.py #blog directory, add the following code
from blog.models import Teacher,Group##This is not in step 8
def orm_handle_db(request):
  test1 = Teacher(id=1,name='runoob',teacher_number='10')
  test2 = Group(id=1,group_name='runoob') ##This is not in step 8
  test1.save()
  test2.save()##This is not in step 8
  return render_to_response('orm_handle_db.html')

10. For table linking operations in a single library (1-to-1, many-to-1, many-to-many). See the video if needed. I really don't want to use foreign keys

11. The table link operation of Kua library is not supported by django, and it needs to be operated by bypassing orm. see summary document

Summary: use ORM for simple operations, and bypass ORM for complex operations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325182734&siteId=291194637