Skip to content

Commit 97c663f

Browse files
committed
update managers
1 parent a1e28ca commit 97c663f

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/polymorphic/managers.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
The manager class for use in the models.
33
"""
44

5+
import inspect
6+
57
from django.contrib.contenttypes.models import ContentType
6-
from django.db import models
8+
from django.db import DEFAULT_DB_ALIAS, models
79

810
from polymorphic.query import PolymorphicQuerySet
911

@@ -62,23 +64,35 @@ def create_from_super(self, obj, **kwargs):
6264
returns obj as an instance of cls.
6365
"""
6466
cls = self.model
65-
import inspect
6667

6768
scls = inspect.getmro(cls)[1]
6869
if scls is not type(obj):
6970
raise TypeError(
7071
"create_from_super can only be used if obj is one level of inheritance up from cls"
7172
)
72-
ptr = "{}_ptr_id".format(scls.__name__.lower())
73-
kwargs[ptr] = obj.id
73+
74+
import ipdb
75+
76+
ipdb.set_trace()
77+
parent_link_field = None
78+
for parent, field in cls._meta.parents.items():
79+
if parent is scls:
80+
parent_link_field = field
81+
break
82+
if parent_link_field is None:
83+
raise TypeError(f"Could not find parent link field for {scls.__name__}")
84+
kwargs[parent_link_field.name] = obj.id
85+
7486
# create the new base class with only fields that apply to it.
7587
nobj = cls(**kwargs)
7688
nobj.save_base(raw=True)
7789
# force update the content type, but first we need to
7890
# retrieve a clean copy from the db to fill in the null
7991
# fields otherwise they would be overwritten.
80-
nobj = obj.__class__.objects.get(pk=obj.pk)
81-
nobj.polymorphic_ctype = ContentType.objects.get_for_model(cls)
92+
nobj = obj.__class__.objects.using(obj._state.db or DEFAULT_DB_ALIAS).get(pk=obj.pk)
93+
nobj.polymorphic_ctype = ContentType.objects.using(
94+
obj._state.db or DEFAULT_DB_ALIAS
95+
).get_for_model(cls)
8296
nobj.save()
8397

8498
return nobj.get_real_instance() # cast to cls

0 commit comments

Comments
 (0)