简体   繁体   中英

Can a single model object be a parent of multiple child objects?

In a Django project, I have a somewhat interesting problem and I am looking for the best and most robust solution. I want to have a parent object that is subclassed by multiple children who can share the parent.

For example, I have the following classes:

class Person(models.Model):
    name = models.CharField(max_length=123)

class Farmer(Person):
    pass

class Preacher(Person):
    pass

Is there a way to have an instance of Person that is both a Farmer and a Preacher?

If this is not possible or reasonable, would a better solution be to simply have a OneToOne relationship between them, like so:

class Person(models.Model):
    name = models.CharField(max_length=123)

class Farmer(models.Model):
    person = models.OneToOne(Person)

class Preacher(models.Model):
    person = models.OneToOne(Person)

Inheritance is not a great idea here. Use the OneToOne relationship instead. @mattm's claim that it doesn't support multiple inheritance is incorrect; the one-to-one limitation is per table , so you can indeed have a person who appears once in the Farmer table and once in the Preacher table.

Inheritance does exist in the database world, but it is not perfectly implemented by PostgreSQL at least, and since Postgres tends to have good standards conformance overall, this doesn't bode well for other database systems. I would not recommend relying on table inheritance unless you've reviewed the database system you will be using and confirmed it can support every aspect of your use case. In practice, this effort is not worth it when you can just use foreign keys to achieve much the same effect. Foreign keys and unique constraints (the building blocks of OneToOne) are very well supported on all modern database systems and will work correctly.

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