[Answer]-Getting data from other database

1๐Ÿ‘

โœ…

I assume you want django admin to only ready the OCS database.

First of all you need to define the external database in the DATABASES settings:

DATABASES = {
    'default': {
        ... django db settings here ...
    },
    'ocs_db': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

You can give python manage.py inspectdb --database ocs_db a try;
inspectdb looks up the tables on the db and dumps the model definition as a python module.
If this does not work then you have to do it manually.

Then you want django not to manage that table (so that no rows will be deleted, and no operation against the table will be done), you can do that via the Meta managed option.

I suggest you to write a base class with this option (and eventually other customisations you need for all OCS models).

class OCSBaseModel(models.Model):

    def save(self):
        """
        avoid inserts / edits from model
        """
        return 

    class Meta():
        abstract = True
        managed = False


class Workstation(OCSBaseModel):
    ...

As last step you need to instruct Django to use the right db for the OCS models.

For this you need to write a database router as documented here

or implement a django model manager for OCS models that marks every querysets to the database.
eg.

class OCSModelManager(models.Manager):
    def get_query_set(self):
        return super(OCSModelManager, self).get_query_set().using('ocs_db')

Please note that I did not test any of this code ๐Ÿ˜‰

Leave a comment