bllli
12/26/2017 - 6:26 AM

工作中使用Django的一些记录

工作中使用Django的一些记录

dump出数据

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

load

python manage.py loaddata db.json

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

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

http://www.wklken.me/posts/2015/03/03/python-base-datetime.html#4-huo-qu-dang-tian-kai-shi-he-jie-shu-shi-jian-000000-235959

获取当天开始和结束时间(00:00:00 23:59:59)

>>> datetime.datetime.combine(datetime.date.today(), datetime.time.min)
datetime.datetime(2015, 1, 12, 0, 0)
>>> datetime.datetime.combine(datetime.date.today(), datetime.time.max)
datetime.datetime(2015, 1, 12, 23, 59, 59, 999999)

双库配置

使用场景

数据后台
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

使用注意事项

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