allow_migrateをmodel_name指定できない?

allow_migrateメソッドではmodel_nameを使用してモデルごとにデータベースを指定することができます。以下はその例です:

python
class MyAppRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'value_search': return 'value_search' elif model._meta.app_label == 'forest_packer': return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'value_search': return 'value_search' elif model._meta.app_label == 'forest_packer': return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'value_search' and obj2._meta.app_label == 'value_search': return True elif obj1._meta.app_label == 'forest_packer' and obj2._meta.app_label == 'forest_packer': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'value_search' and app_label == 'value_search': return True elif db == 'default' and app_label == 'forest_packer': # モデル名が指定されている場合の例 if model_name in ['model1', 'model2']: return True return None

allow_migrateメソッド内でmodel_nameを使用して特定のモデルに対して条件を指定できます。ただし、この例ではmodel_name['model1', 'model2']に含まれる場合のみTrueを返すようにしています。必要に応じて条件を変更してください。

未分類

Posted by ぼっち