Ticket #13432: one_to_one_multidb.diff

File one_to_one_multidb.diff, 2.4 KB (added by Benjamin Wohlwend, 15 years ago)
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 1e016fa..1ba81af 100644
    a b class SingleRelatedObjectDescriptor(object):  
    222222            return getattr(instance, self.cache_name)
    223223        except AttributeError:
    224224            params = {'%s__pk' % self.related.field.name: instance._get_pk_val()}
    225             db = router.db_for_read(instance.__class__, instance=instance)
     225            db = router.db_for_read(self.related.model, instance=instance)
    226226            rel_obj = self.related.model._base_manager.using(db).get(**params)
    227227            setattr(instance, self.cache_name, rel_obj)
    228228            return rel_obj
  • tests/regressiontests/multiple_database/tests.py

    diff --git a/tests/regressiontests/multiple_database/tests.py b/tests/regressiontests/multiple_database/tests.py
    index e4929f4..da8aac7 100644
    a b class AuthTestCase(TestCase):  
    13101310        management.call_command('dumpdata', 'auth', format='json', database='other')
    13111311        self.assertTrue('alice@example.com' in self.stdout.getvalue())
    13121312
     1313class OneToOneProfileRouter(object):
     1314    def db_for_read(self, model, **hints):
     1315        return self._db_for_model(model)
     1316
     1317    def db_for_write(self, model, **hints):
     1318        return self._db_for_model(model)
     1319
     1320    def allow_syncdb(self, db, model):
     1321        return db == self._db_for_model(model)
     1322
     1323    def _db_for_model(self, model):
     1324        if model == UserProfile:
     1325            return 'other'
     1326        else:
     1327            return 'default'
     1328
     1329class OneToOneMultiDBTestCase(TestCase):
     1330    multi_db = True
     1331
     1332    def setUp(self):
     1333        self.old_routers = router.routers
     1334        router.routers = [OneToOneProfileRouter()]
     1335
     1336    def tearDown(self):
     1337        router.routers = self.old_routers
     1338
     1339    def test_one_to_one_multidb(self):
     1340        alice = User.objects.create_user('alice', 'alice@example.com')
     1341        alice_profile, created = UserProfile.objects.get_or_create(user=alice, flavor='chocolate')
     1342        alice = User.objects.get(username='alice')
     1343        try:
     1344            alice.userprofile
     1345        except UserProfile.DoesNotExist:
     1346            self.fail("alice's userprofile should be found on the 'other' database")
     1347
    13131348class UserProfileTestCase(TestCase):
    13141349    def setUp(self):
    13151350        self.old_auth_profile_module = getattr(settings, 'AUTH_PROFILE_MODULE', None)
Back to Top