Skip to content

Commit e9104cc

Browse files
committed
Merge pull request #19 from JBKahn/django-1.9-hints
Support DJango 1.9 passing in the model instead of the model name.
2 parents fcf95ad + 2d2c56b commit e9104cc

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

django_sharding_library/router.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,20 +73,23 @@ def allow_migrate(self, db, app_label, model_name=None, **hints):
7373
if settings.DATABASES[db].get('PRIMARY', None):
7474
return False
7575
model_name = model_name or hints.get('model_name')
76+
model = hints.get('model')
77+
if model:
78+
model_name = model.__name__
7679
if not model_name:
7780
raise InvalidMigrationException(
78-
'Model name not provided in migration, please pass a `model_name` with the hints passed into the migration.'
81+
'Model name not provided in migration, please pass a `model_name` or `model` with the hints passed into the migration.'
7982
)
8083

8184
# Sometimes, when extending models from another app i.e. the User Model, the app label
8285
# is the app label of the app where the change is defined but to app with the model is
8386
# passed in with the model name.
8487
try:
85-
app = apps.get_app_config(app_label)
88+
app = apps.get_app_config(app_label)
8689
model = app.get_model(model_name)
8790
except LookupError:
88-
app_label = model_name.split('.')[0]
89-
app = apps.get_app_config(app_label)
91+
app_label = model_name.split('.')[0]
92+
app = apps.get_app_config(app_label)
9093
model = app.get_model(model_name[len(app_label) + 1:])
9194

9295
single_database = self.get_specific_database_or_none(model)

tests/test_router.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,14 @@ def test_requires_model_name_to_be_passed_in(self):
168168
hints = {'model_name': 'User'}
169169
self.sut.allow_migrate(db='default', app_label='tests', **hints)
170170

171+
def test_requires_model_to_be_passed_in(self):
172+
from django.contrib.auth import get_user_model
173+
with self.assertRaises(InvalidMigrationException):
174+
self.sut.allow_migrate(db='default', app_label='tests')
175+
176+
hints = {'model': get_user_model()}
177+
self.sut.allow_migrate(db='default', app_label='tests', model_name=None, **hints)
178+
171179
def test_migrate_replica_will_not_work(self):
172180
self.assertFalse(self.sut.allow_migrate(db='app_shard_001_replica_001', app_label='tests', model_name='TestModel'))
173181
self.assertTrue(self.sut.allow_migrate(db='app_shard_001', app_label='tests', model_name='TestModel'))

0 commit comments

Comments
 (0)