将OneToOneField转换为MultipleTableInheritance [英] Convert OneToOneField to MultipleTableInheritance

查看:100
本文介绍了将OneToOneField转换为MultipleTableInheritance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构建此问​​题:哪个更好:外键或模型继承?

我想知道是否可以用MTI替换OneToOne字段?

I would like to know if it is possible to replace a OneToOne field by MTI?

Ak

我有:

class GroupUser(models.Model):
    group = models.OneToOneField(Group)
    ...other fields....

,我想要:

class GroupUser(Group):
    ...other fields....

我认为应该更快,不是吗?

I think that should be faster, or not?

可以吗?

推荐答案

它不会更快,因为你的父类对象如果您使用具体的继承(听起来就像这样),在数据库中仍然会有一个字段链接到子类,所以在技术上效率与OneToOne字段相同。

It won't be faster, because your parent class object will still have a field in the database that links to the child class if you are using concrete inheritance(and sounds like it would be), so technically the efficiency is the same as OneToOne field.

选择也是基于业务逻辑。继承用于具有相似类型的情况,以便可以在父类中定义公共字段/方法,并减少一些重复代码。您的示例听起来像 GroupUser 完全是两个不同的东西,很可能它们不共享许多常见属性要么,所以除非我误会你的意图,OneToOneField是一个更好的候选人。

The choice is also based on the business logic. Inheritance is used for the situations where you have things that are of similar type, so that you could define common fields/methods in the parent class and reduce some repetitive code. From your example sounds like Group and GroupUser are totally two different things, most likely they don't share many common attributes either, so unless I misunderstand your intention, OneToOneField is a better candidate.

这篇关于将OneToOneField转换为MultipleTableInheritance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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