gpt4 book ai didi

python - 如何减少 Django 在查询子模型属性时调用数据库的次数?

转载 作者:太空宇宙 更新时间:2023-11-04 04:41:10 25 4
gpt4 key购买 nike

我很难弄清楚基本的优化,希望能提供一些见解或有人为我指明正确的方向。

简化模型:

class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True, db_index=True)
modified = models.DateTimeField(auto_now=True)

class Meta:
abstract = True

class Venue(TimeStampedModel):
name = models.CharField(unique=True, max_length=200, db_index=True)

class Offer(TimeStampedModel):
venue_associated = models.ForeignKey(Venue, on_delete=models.CASCADE, db_index=True)
content = models.TextField(max_length=500, db_index=True)

简化 View :

class MapView(ListView):
fields = ["name"]
model = Venue
template_name = "venues/venue_map.html"

简化模板:

{% for venue in venue_list %}
{{ venue.name }}
{{ venue.offer_set.latest.created }}
{{ venue.offer_set.latest.content }}
{% endfor %}

这会产生大量的数据库调用 (~400)。遍历整个 venue_list 只会创建一个调用(+1 未关联),但两个 offer_set 调用会创建新调用(每个 200)。

因此我假设为 Venue 模型创建一个单独的属性“latest”会有所帮助,因为它至少会处理“latest”调用的加倍,但没有。我还尝试着重写通用的 ListView 方法,但这并没有让我得到任何帮助。

可能有一种我没有看到的方法。目前,我所能想到的只是向 Venue 模型添加额外的字段来复制信息,并且需要额外的逻辑来管理它。

编辑:

我试过:queryset = Venue.objects.prefetch_related('offer_set')

它所做的只是创建一个额外的查询:

SELECT ••• FROM "offers_offer" WHERE "offers_offer"."venue_associated_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200)

相同的 400 个查询(具有不同的 id 值)仍在运行:

SELECT ••• FROM "offers_offer" WHERE "offers_offer"."venue_associated_id" = 1 ORDER BY "offers_offer"."order" ASC, "offers_offer"."created" DESC LIMIT 1

最佳答案

一般情况下,您可以使用 prefetch_related(..) 在额外查询中获取所有相关模型,所以我们可以将其添加到 queryset ListView 的属性:

class MapView(ListView):
fields = ["name"]
model = Venue
<b>queryset = Venue.objects.prefetch_related('offer_set')</b>
template_name = "venues/venue_map.html"

关于python - 如何减少 Django 在查询子模型属性时调用数据库的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581508/

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