I've got:
class User(models.Model):
name = models.CharField()
class Worker(User):
role = models.CharField()
I've imported all of Users from a legacy database. And I can obviously make:
bob = User.objects.get(name='bob')
which returns bob
instance.
But now, I need to create a Worker instance that inherits from bob
? I first thought of this:
MyWorker = Worker.objects.create(
pk = bob.pk,
role = 'chief')
which returns a new Worker instance but not correlated to Bob user as I wanted. How could I create this Worker instance based on bob
instance then?
Here is the correct and complete way to solve this problem. Multi-table inheritance is just OneToOneField relation between User and Worker, this is the point get here.
To create a subclass Worker from an User instance, you should do this:
user = User.objects.get(name='bob')
worker = Worker(user_ptr=user, role='chief')
worker.__dict__.update(user.__dict__)
worker.save()
An important point here is the dict update between both instances.
This question may be duplicated but to have the complete response you have to search in comments. The dict update trick is a big part of the solution.