python中django操作多数据库的方法(代码)


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于python中django操作多数据库的方法(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

1、添加数据库路由分配文件

在项目文件夹里创建‘database_router’文件。将下面的代码复制到该文件里。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

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

2、在settings.py文件中配置多数据库

阅读剩余部分

相关阅读 >>

学习Python需要哪些基础知识?

初学Python看什么书?

流畅的Python适合入门吗

Python如何写一个函数判断回文数?

关于Python 下划线使用场景

Python怎么安装tensorflow

如何调用Python中的内置函数?(实例解析)

使用xcode怎么编写并运行Python

Python如何调用requests包

Python launcher 可以卸载吗?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...