-1

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?

Emilio Conte
  • 1,105
  • 10
  • 29
  • 1
    Instances don't inherit from instances - classes inherit from classes. What are you actually trying to achieve? – jonrsharpe Jul 10 '15 at 13:50
  • Are trying to create a copy of `bob` but as an instance of `B`? I'm not sure that's what you *really* want to do. Could you provide an actual example of what you want to achieve and why you think this is the way to do it? – kylieCatt Jul 10 '15 at 13:52
  • @jonrsharpe You're right. In this particular case (data migration) I need an Instance to inherit from an other instance. It's why it doesn't work. – Emilio Conte Jul 10 '15 at 13:58
  • Show your two models completely – joel goldstick Jul 10 '15 at 14:03
  • Your question is unclear, but you can add a foreign key to Worker which will relate to the User model. – joel goldstick Jul 10 '15 at 14:07
  • @joelgoldstick I've edited my question. Yes, a FK would be a solution. I thought to bypass this using inheritance. I surely misunderstand inheritance in django models. – Emilio Conte Jul 10 '15 at 14:09
  • Your models are ok. So Provider is a model that has everything that Company has, but also adds some new attributes. Django does have model inheritance: https://docs.djangoproject.com/en/1.8/topics/db/models/#model-inheritance – joel goldstick Jul 10 '15 at 14:17
  • 1
    Is [this](http://stackoverflow.com/q/10640789/473232) what you're trying to do? – dgel Jul 10 '15 at 14:21
  • @joelgoldstick and so? Do you have an idea how to create my Provider from an existant company? – Emilio Conte Jul 10 '15 at 14:22
  • Look at the link i sited. I believe you are looking for case 2. Multi table inheritance – joel goldstick Jul 10 '15 at 14:25

1 Answers1

0

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.

Community
  • 1
  • 1
Emilio Conte
  • 1,105
  • 10
  • 29