سؤال

I have the following database settings in django:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
      'NAME': 'default_db',
    },
    'otherdb': {
        'ENGINE': 'django.db.backends.mysql', 
      'NAME': 'other_db',
    }
}

default model is:

class Notification(models.Model):

otherdb model is:

class Entity(models.Model):

In my view code I simply do:

entities = Entity.objects.get(pk=pk)

    for entity in entities:
        print entity

According to the django docs, django will do the database routing for you. I have models for both databases. When I run this i get an error that:

1146, "Table 'default_db.Entity' doesn't exist"

It should be looking for other_db.Entity

Is there something I need to do to make the routing occur on my ec2 instance?

هل كانت مفيدة؟

المحلول

I overrode the routing class as mentioned here:

https://docs.djangoproject.com/en/dev/topics/db/multi-db/#topics-db-multi-db-hints

I used the following functions:

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

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'auth_db'
        return None
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top