问题描述
我在此处多表继承会导致性能问题,建议使用显式的OneToOneField.
I read here that multi-table inheritance can cause performance issues, and instead explicit OneToOneField is recommended.
这是我的情况:
class Product(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=10)
category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False)
class Book(Product):
publisher = models.CharField(max_length=50)
author = models.CharField(max_length=50)
isbn = models.CharField(max_length=50)
class Shoes(Product):
size = models.PositiveSmallIntegerField()
colour = models.CharField(max_length=20, choices=[('black', 'Black'), ('white', 'White')])
当多表继承为以完全相同的方式实现:
place_ptr = models.OneToOneField(
Place, on_delete=models.CASCADE,
parent_link=True,
)
如果所有情况都是如此,我想知道如何更改我的模型,以便他们使用显式的OneToOneField.因此,如果我创建Book实例,则 Product.objects.all()
也应检索该Book实例.
If this is true despite everything, I would like to know how could I alter my models so they use explicit OneToOneField. So, if I create a Book instance, Product.objects.all()
should retrieve that instance of Book, too.
推荐答案
我对基于多种原因的多表继承会导致性能问题的结论有些怀疑:
I'd be a bit skeptical of the conclusion that multi-table inheritance causes performance issues for a variety reasons:
- 该问题已有5年历史,因此答案可能已过时.
- 此答案与结论相矛盾
- 给出为什么模型继承不好的唯一解释是它需要左联接或
- That question is 5 years old, so the answers might be outdated.
- this answer contradicts that conclusion
- The only explanations given for why model inheritance is bad are that it requires LEFT JOINs or
上面的说法可能是正确的,但没有解释如何显式的 OneToOneField
更好,这是user193130的.
The above statement may be true, but it doesn't explain how explicit OneToOneField
s are better, which is the main premise of user193130's answer.
您应该问自己的真正问题是,我应该将表x和表y连接起来吗?,事实证明,这是一个极其复杂的问题.
The real question you should ask yourself is, should I join table x and table y?, which, as turns out, is an extremely complicated question.
以下是与此主题相关的资源列表,其中大多数支持我的怀疑态度:
Here is a list of resources related to this topic, most of which support my skepticism:
丹妮·赫拉拉(dani herrara)回复的
:
to which dani herrara replies:
这篇关于模型继承:显式OneToOneField与隐式多表继承OneToOneField的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!