|
2 | 2 | The manager class for use in the models. |
3 | 3 | """ |
4 | 4 |
|
5 | | -from django.db import models |
| 5 | +import inspect |
| 6 | + |
| 7 | +from django.contrib.contenttypes.models import ContentType |
| 8 | +from django.db import DEFAULT_DB_ALIAS, models |
6 | 9 |
|
7 | 10 | from polymorphic.query import PolymorphicQuerySet |
8 | 11 |
|
@@ -49,3 +52,44 @@ def not_instance_of(self, *args): |
49 | 52 |
|
50 | 53 | def get_real_instances(self, base_result_objects=None): |
51 | 54 | return self.all().get_real_instances(base_result_objects=base_result_objects) |
| 55 | + |
| 56 | + def create_from_super(self, obj, **kwargs): |
| 57 | + """Creates an instance of self.model (cls) from existing super class. |
| 58 | + The new subclass will be the same object with same database id |
| 59 | + and data as obj, but will be an instance of cls. |
| 60 | +
|
| 61 | + obj must be an instance of the direct superclass of cls. |
| 62 | + kwargs should contain all required fields of the subclass (cls). |
| 63 | +
|
| 64 | + returns obj as an instance of cls. |
| 65 | + """ |
| 66 | + cls = self.model |
| 67 | + |
| 68 | + scls = inspect.getmro(cls)[1] |
| 69 | + if scls is not type(obj): |
| 70 | + raise TypeError( |
| 71 | + "create_from_super can only be used if obj is one level of inheritance up from cls" |
| 72 | + ) |
| 73 | + |
| 74 | + parent_link_field = None |
| 75 | + for parent, field in cls._meta.parents.items(): |
| 76 | + if parent is scls: |
| 77 | + parent_link_field = field |
| 78 | + break |
| 79 | + if parent_link_field is None: |
| 80 | + raise TypeError(f"Could not find parent link field for {scls.__name__}") |
| 81 | + kwargs[parent_link_field.get_attname()] = obj.id |
| 82 | + |
| 83 | + # create the new base class with only fields that apply to it. |
| 84 | + nobj = cls(**kwargs) |
| 85 | + nobj.save_base(raw=True) |
| 86 | + # force update the content type, but first we need to |
| 87 | + # retrieve a clean copy from the db to fill in the null |
| 88 | + # fields otherwise they would be overwritten. |
| 89 | + nobj = obj.__class__.objects.using(obj._state.db or DEFAULT_DB_ALIAS).get(pk=obj.pk) |
| 90 | + nobj.polymorphic_ctype = ContentType.objects.db_manager( |
| 91 | + using=(obj._state.db or DEFAULT_DB_ALIAS) |
| 92 | + ).get_for_model(cls) |
| 93 | + nobj.save() |
| 94 | + |
| 95 | + return nobj.get_real_instance() # cast to cls |
0 commit comments