gpt4 book ai didi

python - 模型继承: benefits of explicit OneToOneField vs implicit multi-table inheritance OneToOneField

转载 作者:行者123 更新时间:2023-12-01 07:11:16 27 4
gpt4 key购买 nike

我读到here多表继承可能会导致性能问题,建议使用显式 OneToOneField。

这是我的情况:

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')])

我不明白为什么显式 OneToOneField 会带来性能提升,当多表继承是 implemented in exactly the same way 时:

place_ptr = models.OneToOneField(
Place, on_delete=models.CASCADE,
parent_link=True,
)

如果无论如何都是如此,我想知道如何改变我的模型,以便它们使用显式的 OneToOneField。因此,如果我创建一个 Book 实例,Product.objects.all() 也应该检索该 Book 实例。

最佳答案

由于多种原因,我对多表继承导致性能问题的结论有点怀疑:

  • 该问题已有 5 年历史,因此答案可能已经过时。
  • this答案与结论相矛盾
  • 对于模型继承为什么不好的唯一解释是它需要 LEFT JOIN

    The reason using multi-table inheritance is inefficient is because it generates an extra table for the base model, and therefore extra JOINs to access those fields.

上面的说法可能是正确的,但它并没有解释如何显式OneToOneField更好,这是user193130的answer的主要前提.

您应该问自己的真正问题是,我应该连接表 x 和表 y 吗?,事实证明,这是一个极其复杂的问题。

以下是与此主题相关的资源列表,其中大部分支持我的怀疑:

  • dani herrera's answer 的评论:

    "Q: Why are explicit OneToOneFields better? A: You can access directly to related model without left joins." this is somewhat misleading. I think you need joins anyway. The difference is whether you do it explicitly or implicitly. Please correct me if I'm wrong

    dani herrara 回复:

    @eugene, you are right. Be free to improve answer. Thanks!

  • Chris Pratt's answer 的最后几行:

    Using separate models (and tables) only makes sense for the purposes of modularization -- such that you subclass Project to create a specific kind of project that requires additional fields but still needs all the fields of a generic Project.

  • 评论Chris Pratt's other answer :

    It depends on the situation. If there's a clear is-a relationship going on. Like class Dog(Animal), then you should use MTI (If it's called for. Some other form of inheritance may be more appropriate). But, in the case of something like auth.User, a UserProfile is not really a type of User, so OneToOneField makes more sense. However, the BIG caveat there is that UserProfile is used because User cannot be altered. Otherwise, simply adding additional fields to User would be more appropriate

关于python - 模型继承: benefits of explicit OneToOneField vs implicit multi-table inheritance OneToOneField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209460/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com