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.

3
  • 1
    docs.djangoproject.com/en/1.10/topics/db/models/… ? Commented Oct 17, 2016 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. Commented Oct 17, 2016 at 12:40
  • I found a related question stackoverflow.com/questions/9821935/… Commented Oct 18, 2016 at 8:16

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.