python - Django's prefetch_related for count only -


i have situation (the actual code bound in template, , omitted brevity).

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

i've managed considerably reduce total number of queries using django's awesome prefetch_related method.

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

however i'm wondering if situation further optimized. understand prefetch_related retrieves of data associated related models. seeing care amount of related models, , not models themselves, seems query optimized further doesn't retrieve bunch of unnecessary data. there way in django without dropping down raw sql?

you're right, it's wasteful fetch data database if want count. suggest annotation:

threads = (thread.objects.annotate(count('comments', distinct=true))                          .annotate(count('upvotes', distinct=true))) thread in threads:     print(thread.comments__count)     print(thread.upvotes__count) 

see annotation documentation more information.


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -