gpt4 book ai didi

python - 嵌套链与重复信息

转载 作者:行者123 更新时间:2023-11-29 03:02:44 25 4
gpt4 key购买 nike

有一个包含 4 个模型的 models.py。它的标准记录是:

class Main(models.Model):
stuff = models.IntegerField()
class Second(models.Model):
nested = models.ForeignKey(Main)
stuff = models.IntegerField()
class Third(models.Model):
nested = models.ForeignKey(Second)
stuff = models.IntegerField()
class Last(models.Model):
nested = models.ForeignKey(Third)
stuff = models.IntegerField()

还有 Last 模型的另一种变体:

class Last(models.Model):
nested1 = models.ForeignKey(Main)
nested2 = models.ForeignKey(Second)
nested = models.ForeignKey(Third)
stuff = models.IntegerField()

这种方式会节省一些数据库负载吗?

nested1 和 nested2 中的信息会重复 Secod 和 Third 中的字段,甚至可能会过时(幸运的是,在我的情况下不会,因为数据不会更改,只会添加新的)。但是从我的想法来看,当我查看某个主记录的所有最后记录时,它可能会节省数据库负载。或者当我只查找特定最后一项的 Main.id 时。

我说得对吗?

它真的会节省负载还是有更好的做法?

最佳答案

这完全取决于您访问数据的方式。默认情况下,当您访问外键时,Django 会再次调用数据库。所以如果你想减少对数据库的调用,可以使用select_related预取外键中的模型。

关于python - 嵌套链与重复信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20616307/

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