简体   繁体   中英

How to create multiple instance for one-to-one field in django from base model inheritance?

I have two type user model inherit from User model:

class User(AbstractBaseUser):
    user_uuid = models.UUIDField(primary_key=True)

    @property
    def is_manager(self):
        return hasattr(self, 'manager')

    @property
    def is_salesman(self):
        return hasattr(self, 'salesman')

class Manager(User):
    user = models.OneToOneField(User, parent_link=True, db_column='user_uuid')

class Salesman(User):
    user = models.OneToOneField(User, parent_link=True, db_column='user_uuid')

Now, the Manager could be a Salesman too. So I want create the manager instance and salesman instance which both inherit from same user instance. I can do it in that way:

INSERT INTO t_salesman (`user_uuid`, ...) VALUES ('{manager.user.user_uuid}', ...) 

then:

user = User.objects.get(user_uuid='{manager.user.user_uuid}')
assert user.is_manager == True
assert user.is_salesman == True

But I can't create Salesman like below:

manager = Manager.objects.first()
salesman = Salesman.objects.create(user=manager.user)  # thanks @Arpit Solanki
assert salesman.user_uuid == manager.user_uuid  # AssertionError, create new user instance

Is there any way I can do that through Django model without add row in Salesman table by SQL directly?

Any suggestion will be helpful, Thanks!

The reason is that user param is a User object not a Manager object. Since your Manager model has user attribute you can pass it to Salesman model to create a object with same user. See the example below.

manager = Manager.objects.first()
salesman = Salesman.objects.create(user=manager.user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM