gpt4 book ai didi

python - Python/Django Web 应用程序中数据库访问查询的性能优化

转载 作者:行者123 更新时间:2023-11-29 13:55:24 25 4
gpt4 key购买 nike

长话短说

在我维护的 Django 应用程序中,我从 FOR 循环内部进行数据库调用。馊主意;我想把它带到循环之外。这是代码:

for link in context["object_list"]:
try:
latest_reply = link.publicreply_set.latest('submitted_on')
#if latest_reply is something:
#do something
except:
pass

FOR 循环外的数据库调用是什么?如您所见,我正在尝试获取每个 link 对象(外键关系)的 latest publicreply。请注意,并非每个 link 对象都存在 publicreply。我似乎无法全神贯注于如何在循环之外执行此操作。分析告诉我,这种重复调用会增加大量开销。


更多详情:

模型是:

class Link(models.Model):
description = models.TextField(validators=[MaxLengthValidator(500)])
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now_add=True)

class Publicreply(models.Model):
submitted_by = models.ForeignKey(User)
answer_to = models.ForeignKey(Link)
submitted_on = models.DateTimeField(auto_now_add=True)
description = models.TextField(validators=[MaxLengthValidator(250)])

class Seen(models.Model):
seen_status = models.BooleanField(default=False)
seen_user = models.ForeignKey(User)
seen_at = models.DateTimeField(auto_now_add=True)
which_reply = models.ForeignKey(Publicreply, related_name="publicreply_seen_related")

并在顶部的代码片段中添加更多附带代码:

link_ids = [link.id for link in context["object_list"]]
seen_replies = Publicreply.objects.filter(answer_to_id__in=link_ids,publicreply_seen_related__seen_user = user)
for link in context["object_list"]:
try:
latest_reply = link.publicreply_set.latest('submitted_on')
if latest_reply in seen_replies:
#do something
except:
pass

最后,context["object_list"]link 对象的列表。对于 Django 模板中显示的每个 link 对象,如果它有一个 latest_reply,我会将它与某个时间戳进行比较,如果某些条件为真,我会放入视觉标记。

最佳答案

尝试:

latest_replys = Publicreply.objects.all().order_by('answer_to','-submitted_on').distinct('answer_to')

for reply in latest_replys:
if reply in in seen_replies:
#do something

关于python - Python/Django Web 应用程序中数据库访问查询的性能优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33319059/

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