我如何优化 Djnago ORM 请求?

问题描述 投票:0回答:1

如何优化ORM请求,获取GDD需要很多时间。我认为子查询有问题,但通过关系“commune__communemeteo”它需要更长的时间,(communemeteo 大约 100 万)。

  communes = communes.filter(
       communeattribute__date__year=year,
       communeattribute__date__month=month,
       communeattribute__date__day__range=(
           days.get("start_date"),
           days.get("end_date"),
       ),
   )
   gdd_subquery = (
       CommuneMeteo.objects.filter(
           date__range=(start_date, end_date), commune_id=OuterRef("id")
       )
       .values("commune_id")
       .annotate(gdd=Sum((F("temp_min") + F("temp_max")) / Value(2) - Value(TBASE)))
       .values("gdd")[:1]
   )

   communes = communes.annotate(
       plant=Value(f"{plant}", output_field=CharField()),
       size=Sum(F("communeattribute__planted_area"), output_field=FloatField()),
       gdd=Subquery(gdd_subquery, output_field=FloatField()),
   )
   ```
python django orm django-orm
1个回答
0
投票

我没有你的模型,我很难编写代码。您必须在查询集中使用 select_lated() 来表示 FK 字段,或者使用 prefetch_lated() 来表示多个

    CommuneMeteo.objects.select_related('your_fk_fields',).filter(
       date__range=(start_date, end_date), commune_id=OuterRef("id")
   )
   .values("commune_id")
   .annotate(gdd=Sum((F("temp_min") + F("temp_max")) / Value(2) - Value(TBASE)))
   .values("gdd")[:1])

我可以建议的另一件事是,如果您有大数据,请使用 Pandas 和 Numpy。你会花一些时间学习,但我可以向你保证这不是浪费时间。

© www.soinside.com 2019 - 2024. All rights reserved.