简体   繁体   English

在Django中有效地获取相关模型的数量

[英]Get count of related model efficiently in Django

I have a situation something like this (the actual code is bound up in a template, and omitted for brevity). 我遇到类似这样的情况(实际代码绑定在模板中,为简洁起见省略)。

threads = Thread.objects.all()
for thread in threads:
    print(thread.comments.count())
    print(thread.upvotes.count())

I've managed to considerably reduce the total number of queries using Django's awesome prefetch_related method. 我已经设法使用Django的awfome prefetch_related方法大大减少了查询总数。

threads = Thread.objects.prefetch_related('comments').prefetch_related('upvotes')

However I'm wondering if this situation could be further optimized. 但是我想知道这种情况是否可以进一步优化。 From what I understand prefetch_related retrieves all of the data associated with the related models. 据我所知, prefetch_related检索与相关模型关联的所有数据。 Seeing as I only care about the amount of related models, and not about the models themselves, it seems like this query could be optimized further so that it doesn't retrieve a bunch of unnecessary data. 看起来我只关心相关模型的数量,而不关心模型本身,似乎这个查询可以进一步优化,以便它不会检索一堆不必要的数据。 Is there a way to do this in Django without dropping down to raw SQL? 有没有办法在Django中执行此操作而不降低到原始SQL?

You're right, it's wasteful to fetch all that data from the database if all you want to do is get the count. 你是对的,如果要做的就是获取计数,从数据库中获取所有数据是浪费的。 I suggest annotation: 我建议注释:

threads = (Thread.objects.annotate(Count('comments', distinct=True))
                         .annotate(Count('upvotes', distinct=True)))
for thread in threads:
    print(thread.comments__count)
    print(thread.upvotes__count)

See the annotation documentation for more information. 有关更多信息,请参阅注释文档

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

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