Как добавить маршрутизаторы базы данных в проект Django - PullRequest
0 голосов
/ 20 декабря 2018

Здесь я следую инструкциям по обработке нескольких баз данных в одном проекте Django themes / db / multi-db

Я создал два необходимых маршрутизатора.Они сохраняются как ./database_routers/discourse.py и ./database_routers/wordpress.py

Содержимое ./database_routers/discourse.py равно

class DiscourseRouter:
    """
    A router to control all database operations on models in the
    discourse application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read discourse models go to discourse.
        """
        if model._meta.app_label == 'discourse':
            return 'discourse'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write discourse models go to discourse.
        """
        if model._meta.app_label == 'discourse':
            return 'discourse'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the discourse app is involved.
        """
        if obj1._meta.app_label == 'discourse' or \
           obj2._meta.app_label == 'discourse':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the discourse app only appears in the 'discourse'
        database.
        """
        if app_label == 'discourse':
            return db == 'discourse'
        return None

Содержимое ./database_routers / wordpress.py is

class WordpressRouter:
    """
    A router to control all database operations on models in the
    wordpress application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read wordpress models go to wordpress.
        """
        if model._meta.app_label == 'wordpress':
            return 'wordpress'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write wordpress models go to wordpress.
        """
        if model._meta.app_label == 'wordpress':
            return 'wordpress'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the wordpress app is involved.
        """
        if obj1._meta.app_label == 'wordpress' or \
           obj2._meta.app_label == 'wordpress':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the wordpress app only appears in the 'wordpress'
        database.
        """
        if app_label == 'wordpress':
            return db == 'wordpress'
        return None

Я создал пустой ./database_routers/__init__.py файл

Настройки маршрутизатора базы данных в api / settings Я установил

DATABASE_ROUTERS = ['database_routers.DiscourseRouter', 'database_routers.WordpressRouter']

Когда я пытаюсь посмотреть на проект, используя shell plus I с

 ./manage.py shell_plus

, я получаю

ImportError: Module "database_routers" does not define a "DiscourseRouter" attribute/class

Как добавить маршрутизаторы базы данных в проект Django, чтобы python распознал путьdirectory_name.ClassName

Ответы [ 2 ]

0 голосов
/ 20 декабря 2018

Вы пропустили имена модулей.

DATABASE_ROUTERS = [
    'database_routers.discourse.DiscourseRouter', 
    'database_routers.wordpress.WordpressRouter'
]
0 голосов
/ 20 декабря 2018

Если я вас хорошо понимаю, вы намерены настроить несколько баз данных, верно?Пожалуйста, найдите ниже:

class ExampleDatabaseRouter(object):
    """
    Determine how to route database calls for an app's models (in this case, for an app named Example).
    All other models will be routed to the next router in the DATABASE_ROUTERS setting if applicable,
    or otherwise to the default database.
    """

    def db_for_read(self, model, **hints):
        """Send all read operations on Example app models to `example_db`."""
        if model._meta.app_label == 'example':
            return 'example_db'
        return None

    def db_for_write(self, model, **hints):
        """Send all write operations on Example app models to `example_db`."""
        if model._meta.app_label == 'example':
            return 'example_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """Determine if relationship is allowed between two objects."""

        # Allow any relation between two models that are both in the Example app.
        if obj1._meta.app_label == 'example' and obj2._meta.app_label == 'example':
            return True
        # No opinion if neither object is in the Example app (defer to default or other routers).
        elif 'example' not in [obj1._meta.app_label, obj2._meta.app_label]:
            return None

        # Block relationship if one object is in the Example app and the other isn't.
            return False

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """Ensure that the Example app's models get created on the right database."""
        if app_label == 'example':
            # The Example app should be migrated only on the example_db database.
            return db == 'example_db'
        elif db == 'example_db':
            # Ensure that all other apps don't get migrated on the example_db database.
            return False

        # No opinion for all other scenarios
        return None

Вы также можете прочитать больше введите описание ссылки здесь

...