Search code examples
djangodjango-polymorphic

How to copy a Django Polymorphic object?


Using the django-polymorpic module has been a great way of simplifying object inheritance where a number of subclasses all inherit from, and share several attributes with, a base class. But while almost everything works pretty much like a normal object, the method of wiping out the .pk and calling save() doesn't work? I've tried:

o = MyPolymorphicSubTable.objects.first()
print(o.pk) # 22
o.pk = None
o.save()
print(o.pk) # still 22 -- still the same object

And also tried:

print(o.id) # 22
o.id = None
o.save()
print(o.id) # still 22

anyone have an answer?


Solution

  • There was a hint toward an answer in an old issue on the polymorphic github issues, and finally found an answer. The id (22) of the object is stored as .id (the base table id) and also as .basetablename_ptr (in my case, 'sectioninfo_ptr')-- the latter is not settable but the .pk references the same field, and is settable, so both the two approaches need to be combined:

    o = MyPolymorphicSubTable.objects.first()
    print(o.pk) # 22
    o.pk = None
    o.id = None # both this and the previous line need to be there
    o.save()
    print(o.pk) # 434
    print(o.id) # 434