|
2 | 2 | The manager class for use in the models. |
3 | 3 | """ |
4 | 4 |
|
| 5 | +import inspect |
| 6 | + |
5 | 7 | from django.contrib.contenttypes.models import ContentType |
6 | | -from django.db import models |
| 8 | +from django.db import DEFAULT_DB_ALIAS, models |
7 | 9 |
|
8 | 10 | from polymorphic.query import PolymorphicQuerySet |
9 | 11 |
|
@@ -62,23 +64,35 @@ def create_from_super(self, obj, **kwargs): |
62 | 64 | returns obj as an instance of cls. |
63 | 65 | """ |
64 | 66 | cls = self.model |
65 | | - import inspect |
66 | 67 |
|
67 | 68 | scls = inspect.getmro(cls)[1] |
68 | 69 | if scls is not type(obj): |
69 | 70 | raise TypeError( |
70 | 71 | "create_from_super can only be used if obj is one level of inheritance up from cls" |
71 | 72 | ) |
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 | + |
74 | 86 | # create the new base class with only fields that apply to it. |
75 | 87 | nobj = cls(**kwargs) |
76 | 88 | nobj.save_base(raw=True) |
77 | 89 | # force update the content type, but first we need to |
78 | 90 | # retrieve a clean copy from the db to fill in the null |
79 | 91 | # 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) |
82 | 96 | nobj.save() |
83 | 97 |
|
84 | 98 | return nobj.get_real_instance() # cast to cls |
0 commit comments