views:

236

answers:

2

When I use multi-table inheritance, Django creates two tables - one for the base class, and one for the derived one, pointing to the first. Is there a way to keep the base table entry while deleting the derived one, and create another entry for another model?

To put it simpler: I have models: A, B(derived from A), C(derived from A). I want to convert an object of type B to type C. Copying is not a good solution because A serves as a set of items, so items point to it with a ForeignKey.

A: 

There is no built-in way to do this. If you need to preserve the entry in the base table because FKs are pointing to it, you'll have to write some manager methods to manipulate the B and C tables using raw SQL.

If you're using an RDBMS that doesn't support referential integrity, you might be able to just copy the data, delete the B instance, and create the C instance with the PK manually set to B's PK.

Carl Meyer
MySQL has supported referential integrity for over 5 years now whenever InnoDB is uses as the engine (i.e. most modern production installations)
Adam Nelson
I know, just had to get a dig in anyway :-)
Carl Meyer
A: 

If there's no built-in way, then I think doing it manually is not so bad - make c a copy of b, then do b.items.update(itemset=c).

hmp