0

Let's say I have class A and class B that belong in database Y which is not the default database in my Django application.

class A(models.Model):
    attA = models.CharField(max_length = 1024)

class B(models.Model):
    forA = models.ForgeinKey(A)
    attB = models.CharField(max_length = 8)

class BForm(forms.ModelForm):
    class Meta:
         model = B

In this case, tables A and B both reside in my non-default database. How do I specify to use this database to look up these tables instead of looking in my default one. In my view I have

form = BForm()

But I get an error saying Programming error: relation does not exist, since it is looking in my default db and not the alt one where the tables are actually present. How do I resolve this?

tks
  • 55
  • 6

1 Answers1

0

You should define a database router to tell Django to store which model in which database. [docs]

An example would be:

Settings.py

DATABASE_ROUTERS = ['path.to.YourRouter']

router.py

class YourRouter(object): 
    def db_for_read(self, model, **hints):
        if model.__class__.__name__ in ['A', 'B']:
            return 'secondDB'
        return 'default'

    def db_for_write(self, model, **hints):
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        return True
Mohammad Jafar Mashhadi
  • 4,102
  • 3
  • 29
  • 49