简体   繁体   English

Django queryset以字典运行缓慢

[英]Django queryset to dict running slow

I am querying objects in Django and then creating a dictionary comprehension for those objects. 我正在Django中查询对象,然后为这些对象创建字典理解。 When I do a speed test the function takes .9 seconds, even though it is only querying 104 objects. 当我进行速度测试时,即使只查询104个对象,该功能也要花费0.9秒钟。 What is taking the code so long? 这么长时间的代码是什么? I am running with DEBUG=False and have tried using values_list(). 我正在使用DEBUG = False运行,并尝试使用values_list()。 Also, I am using postgresql. 另外,我正在使用postgresql。

@speed_test
def find_user_fc_ids(user_id=1):
    try:
        flavor_compounds = UserFlavorCompound.objects.filter(user_id__in=user_id)
        return {flavor.flavor_id: flavor.score for flavor in flavor_compounds}
    except UserFlavorCompound.DoesNotExist:
        flavor_compounds = UserFlavorCompound.objects.filter(user_id__in=1)
        return {flavor.flavor_id: flavor.score for flavor in flavor_compounds}

Maybe you'd checkout your models. 也许您会检查您的模型。 If you use ForeignKey you'd probable query them with select_related. 如果您使用ForeignKey,则可能会使用select_related查询它们。 Or if you're using ManyToMany fields you'd call them with prefetch related. 或者,如果您使用的是ManyToMany字段,则可以将它们称为与预取相关。

These optimizations improves your your performance quite well i guess. 我猜这些优化可以很好地改善您的性能。

You can check out: prefetch_related and select_related from official django docs. 您可以从django官方文档中检出: prefetch_relatedselect_related

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM