關於django操做orm的一些事--反向生成orm、鏈接多個數據庫

1. django反向生成orm的類代碼

使用命令python manage.py inspectdb > app01/models.py,注意,我這裏的app01是app的名字。html

2.django鏈接多個數據庫

在不少狀況下,一個項目裏面不止一個app,也不止使用一個庫,那麼就面臨着鏈接多個數據庫的問題。python

那麼先來講說,如何鏈接使用多個app鏈接多個數據庫:mysql

以mysql爲例:sql

在settings.py文件裏面:數據庫

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': "db0",
       'USER': 'root',
       'PASSWORD': '123456',
       'HOST': '127.0.0.1',
       'PORT': '3306',
  },
   'db1': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'db1',
       'USER': 'root',
       'PASSWORD': '123456',
       'HOST': '127.0.0.1',
       'PORT': '3306',
  },
   'db2': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'db2',
       'USER': 'root',
       'PASSWORD': '123456',
       'HOST': '127.0.0.1',
       'PORT': '3306',
  },
}
# 此配置,列表裏寫:   項目工程的名字.database_router.DatabaseAppsRouter
DATABASE_ROUTERS = ['your_project_name.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
   # 這裏面對應的是,app的名字和數據庫的名字(在上面註冊的)
   'app01': 'default',
   'app02': 'db1',
   'app03': 'db2',
}

另外,爲了可以訪問到不一樣的庫,還須要加一個文件,寫上數據庫的路由:django

你的項目名/項目名的文件夾下(舉例:好比我起了一個項目叫test_django,那麼在test_django/test_django,也就是和settings.py同級目錄),新建一個文件叫:服務器

database_router.py,寫入以下代碼:session

# database_router.py
from django.conf import settings

DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING


class DatabaseAppsRouter(object):
   """
  A router to control all database operations on models for different
  databases.

  In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
  will fallback to the `default` database.

  Settings example:

  DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
  """

   def db_for_read(self, model, **hints):
       """"Point all read operations to the specific database."""
       if model._meta.app_label in DATABASE_MAPPING:
           return DATABASE_MAPPING[model._meta.app_label]
       return None

   def db_for_write(self, model, **hints):
       """Point all write operations to the specific database."""
       if model._meta.app_label in DATABASE_MAPPING:
           return DATABASE_MAPPING[model._meta.app_label]
       return None

   def allow_relation(self, obj1, obj2, **hints):
       """Allow any relation between apps that use the same database."""
       db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
       db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
       if db_obj1 and db_obj2:
           if db_obj1 == db_obj2:
               return True
           else:
               return False
       return None

   def allow_syncdb(self, db, model):
       """Make sure that apps only appear in the related database."""

       if db in DATABASE_MAPPING.values():
           return DATABASE_MAPPING.get(model._meta.app_label) == db
       elif model._meta.app_label in DATABASE_MAPPING:
           return False
       return None

   def allow_migrate(self, db, app_label, model=None, **hints):
       """
      Make sure the auth app only appears in the 'auth_db'
      database.
      """
       if db in DATABASE_MAPPING.values():
           return DATABASE_MAPPING.get(app_label) == db
       elif app_label in DATABASE_MAPPING:
           return False
       return None

   # for Django 1.4 - Django 1.6
   def allow_syncdb(self, db, model):
       """Make sure that apps only appear in the related database."""

       if db in DATABASE_MAPPING.values():
           return DATABASE_MAPPING.get(model._meta.app_label) == db
       elif model._meta.app_label in DATABASE_MAPPING:
           return False
       return None

   # Django 1.7 - Django 1.11
   def allow_migrate(self, db, app_label, model_name=None, **hints):
       print(db, app_label, model_name, hints)
       if db in DATABASE_MAPPING.values():
           return DATABASE_MAPPING.get(app_label) == db
       elif app_label in DATABASE_MAPPING:
           return False
       return None

那麼,此時,你就能夠訪問不一樣的數據庫了。app

3.django多個數據庫反向生成orm代碼

如今,多個庫已經有了,那麼,如何使用不一樣的庫,在不一樣的app裏面生成orm的代碼呢?ui

python manage.py inspectdb --database db1 > app01/models.py

注意,上面的db1是你註冊在settings.py文件下面的DATABASES,裏面的數據庫名字,app01是你的app名字。

 

解決bug:

當遇到bug:

# The error was: (1, "Can't create/write to file '/tmp/#sql_7d33_0.MYI' (Errcode: 13 - Permission denied)")
# Unable to inspect table 'session'

到數據庫所在的服務器上:

chmod 777 /tmp

便可解決此問題。

原文出處:https://www.cnblogs.com/haiguixiansheng/p/11732162.html

相關文章
相關標籤/搜索