Несколько баз данных с использованием маршрутизаторов - PullRequest
0 голосов
/ 24 марта 2020

Я создал приложение с тремя учетными записями приложений, Product и Post, я хочу подключить каждое приложение к другой базе данных, но этого просто не происходит. Пожалуйста, скажите мне, что я делаю неправильно. Это первый раз, когда я пытаюсь использовать несколько баз данных.

setting.py

DATABASE_ROUTERS = ['account.router.AccountRouter', 'Post.router.PostRouter','Product.router.ProductRouter']
DATABASES = {
    'default': {},
    'auth_db': {
        'NAME': 'a_user',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'postgres',
        'PASSWORD': '1234',
        'HOST':'localhost'
    },
    'account_db': {
        'NAME': 'account',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'postgres',
        'PASSWORD': '1234',
        'HOST':'localhost'
    },
    'post_db': {
        'NAME': 'post',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'postgres',
        'PASSWORD': '1234',
        'HOST':'localhost'
    },
    'product_db': {
        'NAME': 'product',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'postgres',
        'PASSWORD': '1234',
        'HOST':'localhost'
    }
}

Product / router.py

class ProductRouter:
    """
    A router to control all database operations on models in the
    auth and contenttypes applications.
    """
    route_app_labels = {'Product',}

    def db_for_read(self, model):
        """
        Attempts to read auth and contenttypes models go to product_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'product_db'
        return None

    def db_for_write(self, model):
        """
        Attempts to write auth and contenttypes models go to product_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'product_db'
        return None

    def allow_relation(self, obj1, obj2):
        """
        Allow relations if a model in the auth or contenttypes apps is
        involved.
        """
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth and contenttypes apps only appear in the
        'product_db' database.
        """
        if app_label in self.route_app_labels:
            return db == 'product_db'
        return None

Аналогично Post / router.py и account / router.py

Product / models.py

User = get_user_model()


class Product(models.Model):
    name = models.CharField(max_length = 30 , unique = True)
    weight = models.DecimalField(decimal_places= 2 , max_digits = 30)
    price = models.BigIntegerField()
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(blank=True, null=True)


    def __str__(self):
        return self.name

    class Meta:
        app_label = 'product_data'

Post / models.py

User = get_user_model()


class Post(models.Model):
    user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
    created_at = models.DateTimeField(default=timezone.now)
    text = models.TextField()
    updated_at = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.text


    def get_absolute_url(self):
        return reverse(
            "posts:single",
            kwargs={
                "username": self.user.username,
                "pk": self.pk
            }
        )

    class Meta:
        ordering = ["-created_at"]
        unique_together = ["user",]
        app_label = 'post_data'

account / models.py

class User(auth.models.User, auth.models.PermissionsMixin):

    def __str__(self):
        return "@{}".format(self.username)

    class Meta:
        app_label = 'user_data'

основной проект dir mayapp /router.py

    """
    A router to control all database operations on models in the
    auth and contenttypes applications.
    """
    route_app_labels = {'auth', 'contenttypes'}

    def db_for_read(self, model, **hints):
        """
        Attempts to read auth and contenttypes models go to auth_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'auth_db'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth and contenttypes models go to auth_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'auth_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the auth or contenttypes apps is
        involved.
        """
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth and contenttypes apps only appear in the
        'auth_db' database.
        """
        if app_label in self.route_app_labels:
            return db == 'auth_db'
        return None

Используется python manage.py migrate --database = account_db

python manage.py migrate --database = post_db

python manage.py migrate --database = product_db

каждый раз, когда выполняется миграция

Операции для выполнения:

Применение всех миграций: admin, auth, contenttypes, session

Выполнение миграций:

Нет применений миграций.

(test) C:\Users\Chetan\Desktop\tradeex_proj\myapp>python manage.py migrate --fake-initial
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\core\management\base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\core\management\commands\migrate.py", line 86, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__
    self.build_graph()
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\db\migrations\recorder.py", line 76, in applied_migrations
    if self.has_table():
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table
    return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\db\backends\base\base.py", line 260, in cursor
    return self._cursor()
  File "C:\Users\Chetan\Envs\test\lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...