Django and read-only database connections

后端 未结 3 1622
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 14:39

Assume a Django application which is supposed to use two MySQL databases:

  • default - for storing data represented by models A and B<
3条回答
  •  爱一瞬间的悲伤
    2021-01-30 15:29

    I encountered the same issue (using Django 1.11) and this question was at the top of my Google results for it.

    Your initial solution is only missing one critical piece. You need to tell Django what database models 'C' and 'D' are using. What worked for me:

    class ExternalModel(models.Model):
        class Meta:
            managed = False
            abstract = True    
            app_label = 'support'
    

    Then tell your database router how to behave when it encounters that app_label in the allow_migrate() section:

        def allow_migrate(self, db, app_label, model_name=None, **hints):
            if app_label == 'support':
                return False
            return (db == 'default')
    

    I'm not sure that is the most-correct-solution in the eyes of the Django team, but effect is allow_migrate() returning False for any models defined with that app_label attribute value.

    The Django documentation on routers doesn't mention this explicitly (or, at least with model code samples that make it clear how the ORM passes the value for 'db' to allow_migrate()), but between the 'app_label' and 'managed' attributes you can get it to work*.

    * In my case the default is postgres and the read-only database is Oracle 12 via cx_Oracle.

提交回复
热议问题