|
2 | 2 | The manager class for use in the models. |
3 | 3 | """ |
4 | 4 |
|
| 5 | +from django.contrib.contenttypes.models import ContentType |
5 | 6 | from django.db import models |
6 | 7 |
|
7 | 8 | from polymorphic.query import PolymorphicQuerySet |
@@ -49,3 +50,35 @@ def not_instance_of(self, *args): |
49 | 50 |
|
50 | 51 | def get_real_instances(self, base_result_objects=None): |
51 | 52 | return self.all().get_real_instances(base_result_objects=base_result_objects) |
| 53 | + |
| 54 | + def create_from_super(self, obj, **kwargs): |
| 55 | + """Creates an instance of self.model (cls) from existing super class. |
| 56 | + The new subclass will be the same object with same database id |
| 57 | + and data as obj, but will be an instance of cls. |
| 58 | +
|
| 59 | + obj must be an instance of the direct superclass of cls. |
| 60 | + kwargs should contain all required fields of the subclass (cls). |
| 61 | +
|
| 62 | + returns obj as an instance of cls. |
| 63 | + """ |
| 64 | + cls = self.model |
| 65 | + import inspect |
| 66 | + |
| 67 | + scls = inspect.getmro(cls)[1] |
| 68 | + if scls is not type(obj): |
| 69 | + raise Exception( |
| 70 | + "create_from_super can only be used if obj is one level of inheritance up from cls" |
| 71 | + ) |
| 72 | + ptr = "{}_ptr_id".format(scls.__name__.lower()) |
| 73 | + kwargs[ptr] = obj.id |
| 74 | + # create the new base class with only fields that apply to it. |
| 75 | + nobj = cls(**kwargs) |
| 76 | + nobj.save_base(raw=True) |
| 77 | + # force update the content type, but first we need to |
| 78 | + # retrieve a clean copy from the db to fill in the null |
| 79 | + # 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) |
| 82 | + nobj.save() |
| 83 | + |
| 84 | + return nobj.get_real_instance() # cast to cls |
0 commit comments