单个模型对象可以是多个子对象的父对象吗? [英] Can a single model object be a parent of multiple child objects?

查看:117
本文介绍了单个模型对象可以是多个子对象的父对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django项目中,我有一个有趣的问题,我正在寻找最好和最强大的解决方案。我想要一个父对象,由多个可以共享父项的子项进行子类化。



例如,我有以下类:

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

class Farmer个人):
通过

class传道人(人):
通过

有没有办法拥有一个既是农民又是传道人的人的实例?



如果这是不可能或不合理的话,那么一个更好的解决办法就是简单地将它们之间的OneToOne关系如下所示:

 类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)


解决方案

继承不是一个好主意。改用OneToOne关系。 @ mattm声称它不支持多重继承是不正确的;一对一的限制是每张表,所以你确实可以有一个人在Farmer表中出现一次,一次在Preacher表中。



继承确实存在于数据库世界中,但它并不完全由 PostgreSQL 至少,因为Postgres总体上具有良好的标准一致性,对于其他数据库系统来说,这并不好。我不建议依赖表继承,除非您已经审查了将要使用的数据库系统,并确认它可以支持用例的各个方面。在实践中,这种努力是不值得的,当您只需使用外键实现大致相同的效果。外键和独特约束(OneToOne的构建块)在所有现代数据库系统上得到很好的支持,并能正常工作。


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.

这篇关于单个模型对象可以是多个子对象的父对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆