djangocross-database

Reference a view from another database in Django


I have a local table which needs to reference a view from a remote database.
Both models are defined in the same app.

Now, I want to use django-import-export to import data from excel or save data from a form.
It keeps reading the wrong database.

My local database is SQLite and the remote one is MSSQL.

Model which is used to access the view:

class EmpView(models.Model):

    class Meta:
        db_table = 'View_Emp'
        managed = False
        indexes = [
            models.Index(fields=['code',]),
        ]

    ...

I set the router to let Django read the remote database when the model is the view otherwise read from the default one:

def db_for_read(self, model, **hints):
   if model.__name__ == 'EmpView':
      return 'emp'
   return 'default'

And the error:

Traceback (most recent call last):
File "E:\Projects\Envs\.as\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "E:\Projects\Envs\.as\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: main.View_Emp

You can tell it reads the local database, but it is supposed to read the remote one.
Where am I wrong?

I found this question, but without answer: "no such table" with multiple database on Django 1.11.1

but I am using a view, it has to be unmanaged...


Solution

  • I think if you want to use remote database than you should define that DB settings in your database settings under settings.py file. and than by using that database name you can access that db table like

    EmpView.objects.using('db_name').filter()
    

    and you should also define your fields in model.