Django Model Inheritance - Multi-Table Inheritance

422 views Asked by At

I am creating a database that has two tables customer and seller and they are both inherited from user table that uses Django auth user. and my question is that is it possible for a user be both customer and seller at the same time?

class BaseUser(models.Model):
# have common fields
is_seller = models.BooleanField()
is_customer = models.BooleanField()
class Meta:
    abstract = True



class Customer(BaseUser):
    # have customer specific fields 



class Seller(BaseUser):
    # have seller specific fields 
2

There are 2 answers

1
Amar On BEST ANSWER

With the current schema you mentioned answer is NO, But you can have

class BaseUser(models.Model):
    # have common fields 
    class Meta:
        abstract = True



class Customer(BaseUser):
    # have customer specific fields 
    class Meta:
        abstract = True


class Seller(BaseUser):
    # have seller specific fields 
    class Meta:
        abstract = True

# this way your user can either inherit customer or seller or both

class User(Seller):
    pass
#OR

class User(Buyer):
    pass
#OR
class User(Seller, Buyer):
    pass
0
Ali On

Yeah, you can have another model, for example Entity, and it have one to one relation with Customer and Seller

class Entity(models.Model):
    customer = models.OneToOneField(Customer)
    seller = models.OneToOneField(Seller)

Now, you can use this model, or customize User model, whatever you want.