4

Assuming the following class structure in django:

class Base(models.Model)
class Derived(Base)

And this base object (which is just Base, not Derived)

b = Base()
b.save()

I'd like to create a derived object from b. Which would be the right way to do this? I've tried:

d = Derived(b)
d = Derived(base_ptr=b)

Thanks

NOTE: I think this is a different question than "How to go from a Model base to derived class in Django?" as what I need is to create a new derived object from an existing base (and only base) object. In that question it checks if the derived class already exists and then returns it. In my case, derived object does not exist.

klautern
  • 129
  • 3
  • 7
  • 26
  • 1
    https://docs.djangoproject.com/en/1.10/topics/db/models/#abstract-base-classes ? – Remi Smirra Oct 17 '16 at 10:50
  • My base class is not abstract. This is multi-table inheritance. After the base object is created, I need to convert it to the derived class, this is at DB level to have a record in derived table linked to base table. – klautern Oct 17 '16 at 12:40
  • I found a related question http://stackoverflow.com/questions/9821935/django-model-inheritance-create-a-subclass-using-existing-super-class – klautern Oct 18 '16 at 08:16

1 Answers1

4

I think I found the solution. The second attemp I tried had the problem it reseted all fields of base object:

d = Derived(base_ptr=b)
d.save()  # Resets all base fields of d

As said in Django model inheritance: create sub-instance of existing instance (downcast)?, this could solve the problem, although it's not the most elegant solution:

d = Derived(base_ptr=b)
d.__dict__.update(b.__dict__)
d.save()
Community
  • 1
  • 1
klautern
  • 129
  • 3
  • 7
  • 26