【问题标题】:How to filter/annotate prefetched objects in django (more efficiently)?如何在 django 中过滤/注释预取的对象(更有效)?
【发布时间】:2021-06-10 09:28:08
【问题描述】:

我想用 prefetch_related 对象过滤查询集。此代码有效,但我想更有效地编写它。你有什么想法吗?

queryset = Song.objects.prefetch_related(
                Prefetch('harmonies', queryset=Harmony.objects.filter(someQuery)))

for s in queryset:
    if s.harmonies.count() > 0:
         songs.append(s.id)
queryset = queryset.filter(id__in=songs)

我尝试了类似的方法,但没有成功。

queryset = queryset.annotate(h_count=Count('harmonies')).exclude(h_count=0)

谢谢你的帮助。

【问题讨论】:

标签: django performance django-queryset django-filter


【解决方案1】:

您可以使用Exists subquery [Django-doc],所以:

from django.db.models import Exists, OuterRef

queryset = Song.objects.filter(
    Exists(Harmony.objects.filter(someQuery, song_id=OuterRef('pk')))
)

这里的song_id=… 是从HarmonysongForeignKey,所以可能会略有不同。

【讨论】:

  • 谢谢。它有效,但我也需要预取相关对象。这对我的目的是必要的。你知道如何有效地合并这个过滤器吗?
  • @Bumaza:您仍然可以添加Prefetch 对象,只需在.filter(...) 之后添加.prefetch_related 子句。
猜你喜欢
  • 1970-01-01
  • 2015-08-25
  • 2021-05-25
  • 1970-01-01
  • 2017-05-05
  • 2019-12-07
  • 2012-04-05
  • 1970-01-01
  • 2019-08-17
相关资源
最近更新 更多