Skip to content

Commit 87a007b

Browse files
ekaplan1bckohanCopilot
committed
Improved support for accessing models when using multiple databases
Co-authored-by: ekaplan1 <[email protected]> Co-authored-by: bckohan <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 9fcebfe commit 87a007b

File tree

4 files changed

+22
-1
lines changed

4 files changed

+22
-1
lines changed

docs/changelog.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Changelog
44
v4.3.0 (202X-XX-XX)
55
-------------------
66

7+
* Fixed `Improved support for accessing models when using multiple databases <https://github.com/jazzband/django-polymorphic/pull/550>`_
78
* Fixed `Caching in inheritance accessor functions <https://github.com/jazzband/django-polymorphic/pull/510>`_
89
* Fixed `Foreign key resolves to parent class when using abstract models <https://github.com/jazzband/django-polymorphic/issues/437>`_
910
* Fixed `Support Q expressions that contain subquery expressions <https://github.com/jazzband/django-polymorphic/pull/572>`_

src/polymorphic/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def accessor_function(self):
207207
rel_obj = field.get_cached_value(self)
208208
except KeyError:
209209
objects = getattr(model, "_base_objects", model.objects)
210-
rel_obj = objects.get(pk=self.pk)
210+
rel_obj = objects.using(self._state.db or DEFAULT_DB_ALIAS).get(pk=self.pk)
211211
field.set_cached_value(self, rel_obj)
212212
return rel_obj
213213

src/polymorphic/tests/settings.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,5 @@
137137
ALLOWED_HOSTS = ["*"]
138138

139139
ROOT_URLCONF = "polymorphic.tests.urls"
140+
141+
USE_TZ = False

src/polymorphic/tests/test_multidb.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,17 @@
1414
ModelY,
1515
One2OneRelatingModel,
1616
RelatingModel,
17+
RelationA,
18+
RelationB,
19+
RelationBase,
1720
)
1821

1922

23+
class AllowAllRelations:
24+
def allow_relation(self, obj1, obj2, **hints):
25+
return True
26+
27+
2028
class MultipleDatabasesTests(TestCase):
2129
databases = ["default", "secondary"]
2230

@@ -118,3 +126,13 @@ def func():
118126

119127
# Ensure no queries are made using the default database.
120128
self.assertNumQueries(0, func)
129+
130+
def test_deletion_cascade_on_non_default_db(self):
131+
base_db1 = RelationA.objects.db_manager("secondary").create(field_a="Base DB1")
132+
base_db2 = RelationB.objects.db_manager("secondary").create(
133+
field_b="Base DB2", fk=base_db1
134+
)
135+
136+
RelationBase.objects.db_manager("secondary").filter(pk=base_db2.pk).delete()
137+
138+
self.assertEqual(RelationB.objects.db_manager("secondary").count(), 0)

0 commit comments

Comments
 (0)