【问题标题】:Django queryset to dict running slowDjango 查询集到 dict 运行缓慢
【发布时间】:2015-05-25 19:04:50
【问题描述】:

我在 Django 中查询对象,然后为这些对象创建字典理解。当我进行速度测试时,该函数需要 0.9 秒,即使它只查询 104 个对象。什么代码花了这么长时间?我正在使用 DEBUG=False 运行并尝试使用 values_list()。另外,我正在使用 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}

【问题讨论】:

  • 试过这个:flavor_compounds = UserFlavorCompound.objects.filter(user_id__in=user_id) 它仍然需要相同的时间:(
  • 这只是函数中的代码,我将对其进行编辑以显示我所拥有的

标签: python django postgresql dictionary django-queryset


【解决方案1】:

也许您会检查您的模型。如果您使用 ForeignKey,您可能会使用 select_related 查询它们。或者,如果您使用的是 ManyToMany 字段,您可以使用与预取相关的方式调用它们。

我猜这些优化可以很好地提高你的表现。

您可以从官方 django 文档中查看:prefetch_relatedselect_related

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2019-04-15
    相关资源
    最近更新 更多