Skip to content

Instantly share code, notes, and snippets.

@bllli
Last active January 10, 2018 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bllli/d0b1ba905b34033f0e02b3827751053e to your computer and use it in GitHub Desktop.
Save bllli/d0b1ba905b34033f0e02b3827751053e to your computer and use it in GitHub Desktop.
工作中使用Django的一些记录

双库配置

使用场景

数据后台
1个读写库,用于存放分析结果数据、数据后台管理   1个另一个项目生产环境的只读库,是本系统统计数据的来源

配置代码

# settings.py
DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        },
        'work': {...}
}

DATABASE_ROUTERS = ['statistic.db_router.DatabaseAppsRouter']  # <- 这个是datebase路由
DATABASE_APPS_MAPPING = {
        # 'app_name': 'database_name',
        'speiyou': 'work',  # <- 另一个项目生产环境的只读库,是本系统统计数据的来源
        'django': 'default',
        'auth': 'default',
        'contenttypes': 'default',
        'sessions': 'default',
        'admin': 'default',
        'accounts': 'default',  # <- 本系统账户管理app
        'statistic': 'default',  # <- 本系统统计app,其model用于存储数据分析结果
}

DATABASE_APPS_MAPPING 中需要存放每一个app的app_name 可以在django_migrations表中找到app的名称

# statistic/db_router.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
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."""
        return True
        # 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

    # 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

使用注意事项

不要试图在两个库间使用聚合查询

从远程服务器把文件拉到本地

scp -r [user]@[ip]:/path/to/file.json /home/bllli/PycharmProjects/path/

dump出数据

python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json

load

python manage.py loaddata db.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment