Query with multiple annotations slows down












0















I've got a query which returns users with additional info
Here are my simplified models:



class Event(..):
creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='event_creator_set')


class Participator(..):
status = models.CharField(..)
event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set')
user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='participations_set')


My method from User Manager:



 def additional_info(self):
from events.models import Participator
participated_events_count = Count(
'participations_set',
distinct=True,
filter=(~Q(participations_set__event__creator=F('id')) & Q(
participations_set__status=Participator.PARTICIPATED))
)
return self.get_queryset()
.annotate(created_events_count=Count('events_set',
distinct=True))
.annotate(followers_count=Count(
'followers_set',
filter=(Q(followers_set__is_following=True)),
distinct=True))
.annotate(
participated_events_count=participated_events_count)


Everything works great without the last annotate, but when I'm trying to add participated_events_count value - query performed up to 30 seconds



UPDATED
If I remove random annotate with Count - query performs very fast










share|improve this question





























    0















    I've got a query which returns users with additional info
    Here are my simplified models:



    class Event(..):
    creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='event_creator_set')


    class Participator(..):
    status = models.CharField(..)
    event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set')
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='participations_set')


    My method from User Manager:



     def additional_info(self):
    from events.models import Participator
    participated_events_count = Count(
    'participations_set',
    distinct=True,
    filter=(~Q(participations_set__event__creator=F('id')) & Q(
    participations_set__status=Participator.PARTICIPATED))
    )
    return self.get_queryset()
    .annotate(created_events_count=Count('events_set',
    distinct=True))
    .annotate(followers_count=Count(
    'followers_set',
    filter=(Q(followers_set__is_following=True)),
    distinct=True))
    .annotate(
    participated_events_count=participated_events_count)


    Everything works great without the last annotate, but when I'm trying to add participated_events_count value - query performed up to 30 seconds



    UPDATED
    If I remove random annotate with Count - query performs very fast










    share|improve this question



























      0












      0








      0








      I've got a query which returns users with additional info
      Here are my simplified models:



      class Event(..):
      creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='event_creator_set')


      class Participator(..):
      status = models.CharField(..)
      event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set')
      user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='participations_set')


      My method from User Manager:



       def additional_info(self):
      from events.models import Participator
      participated_events_count = Count(
      'participations_set',
      distinct=True,
      filter=(~Q(participations_set__event__creator=F('id')) & Q(
      participations_set__status=Participator.PARTICIPATED))
      )
      return self.get_queryset()
      .annotate(created_events_count=Count('events_set',
      distinct=True))
      .annotate(followers_count=Count(
      'followers_set',
      filter=(Q(followers_set__is_following=True)),
      distinct=True))
      .annotate(
      participated_events_count=participated_events_count)


      Everything works great without the last annotate, but when I'm trying to add participated_events_count value - query performed up to 30 seconds



      UPDATED
      If I remove random annotate with Count - query performs very fast










      share|improve this question
















      I've got a query which returns users with additional info
      Here are my simplified models:



      class Event(..):
      creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='event_creator_set')


      class Participator(..):
      status = models.CharField(..)
      event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set')
      user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='participations_set')


      My method from User Manager:



       def additional_info(self):
      from events.models import Participator
      participated_events_count = Count(
      'participations_set',
      distinct=True,
      filter=(~Q(participations_set__event__creator=F('id')) & Q(
      participations_set__status=Participator.PARTICIPATED))
      )
      return self.get_queryset()
      .annotate(created_events_count=Count('events_set',
      distinct=True))
      .annotate(followers_count=Count(
      'followers_set',
      filter=(Q(followers_set__is_following=True)),
      distinct=True))
      .annotate(
      participated_events_count=participated_events_count)


      Everything works great without the last annotate, but when I'm trying to add participated_events_count value - query performed up to 30 seconds



      UPDATED
      If I remove random annotate with Count - query performs very fast







      django django-orm






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 13:03







      Ernst

















      asked Nov 13 '18 at 11:28









      ErnstErnst

      96112




      96112
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You can use .prefetch_related() to lookup the related objects and reduce the number of additional queries.



          return self.get_queryset().prefetch_related('participations_set')/
          ...


          You can use Django Debug Toolbar to get a breakdown of queries on each page.






          share|improve this answer
























          • I added all needed params to prefetch_related(), but it doesn't help. Also I'm building only API, so debug toolbar isn't useful for me

            – Ernst
            Nov 13 '18 at 12:52











          • If you create a simple view with DDT enabled that passes the queryset as context then you will be able to see a breakdown of the repeated queries and exactly what is causing your slowdown. It's hard to tell from your example but I'm guessing the slowdown is because your filter is causing (at least) 3 queries for each object in participations_set

            – bdoubleu
            Nov 13 '18 at 17:52











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280047%2fquery-with-multiple-annotations-slows-down%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You can use .prefetch_related() to lookup the related objects and reduce the number of additional queries.



          return self.get_queryset().prefetch_related('participations_set')/
          ...


          You can use Django Debug Toolbar to get a breakdown of queries on each page.






          share|improve this answer
























          • I added all needed params to prefetch_related(), but it doesn't help. Also I'm building only API, so debug toolbar isn't useful for me

            – Ernst
            Nov 13 '18 at 12:52











          • If you create a simple view with DDT enabled that passes the queryset as context then you will be able to see a breakdown of the repeated queries and exactly what is causing your slowdown. It's hard to tell from your example but I'm guessing the slowdown is because your filter is causing (at least) 3 queries for each object in participations_set

            – bdoubleu
            Nov 13 '18 at 17:52
















          0














          You can use .prefetch_related() to lookup the related objects and reduce the number of additional queries.



          return self.get_queryset().prefetch_related('participations_set')/
          ...


          You can use Django Debug Toolbar to get a breakdown of queries on each page.






          share|improve this answer
























          • I added all needed params to prefetch_related(), but it doesn't help. Also I'm building only API, so debug toolbar isn't useful for me

            – Ernst
            Nov 13 '18 at 12:52











          • If you create a simple view with DDT enabled that passes the queryset as context then you will be able to see a breakdown of the repeated queries and exactly what is causing your slowdown. It's hard to tell from your example but I'm guessing the slowdown is because your filter is causing (at least) 3 queries for each object in participations_set

            – bdoubleu
            Nov 13 '18 at 17:52














          0












          0








          0







          You can use .prefetch_related() to lookup the related objects and reduce the number of additional queries.



          return self.get_queryset().prefetch_related('participations_set')/
          ...


          You can use Django Debug Toolbar to get a breakdown of queries on each page.






          share|improve this answer













          You can use .prefetch_related() to lookup the related objects and reduce the number of additional queries.



          return self.get_queryset().prefetch_related('participations_set')/
          ...


          You can use Django Debug Toolbar to get a breakdown of queries on each page.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 12:22









          bdoubleubdoubleu

          617112




          617112













          • I added all needed params to prefetch_related(), but it doesn't help. Also I'm building only API, so debug toolbar isn't useful for me

            – Ernst
            Nov 13 '18 at 12:52











          • If you create a simple view with DDT enabled that passes the queryset as context then you will be able to see a breakdown of the repeated queries and exactly what is causing your slowdown. It's hard to tell from your example but I'm guessing the slowdown is because your filter is causing (at least) 3 queries for each object in participations_set

            – bdoubleu
            Nov 13 '18 at 17:52



















          • I added all needed params to prefetch_related(), but it doesn't help. Also I'm building only API, so debug toolbar isn't useful for me

            – Ernst
            Nov 13 '18 at 12:52











          • If you create a simple view with DDT enabled that passes the queryset as context then you will be able to see a breakdown of the repeated queries and exactly what is causing your slowdown. It's hard to tell from your example but I'm guessing the slowdown is because your filter is causing (at least) 3 queries for each object in participations_set

            – bdoubleu
            Nov 13 '18 at 17:52

















          I added all needed params to prefetch_related(), but it doesn't help. Also I'm building only API, so debug toolbar isn't useful for me

          – Ernst
          Nov 13 '18 at 12:52





          I added all needed params to prefetch_related(), but it doesn't help. Also I'm building only API, so debug toolbar isn't useful for me

          – Ernst
          Nov 13 '18 at 12:52













          If you create a simple view with DDT enabled that passes the queryset as context then you will be able to see a breakdown of the repeated queries and exactly what is causing your slowdown. It's hard to tell from your example but I'm guessing the slowdown is because your filter is causing (at least) 3 queries for each object in participations_set

          – bdoubleu
          Nov 13 '18 at 17:52





          If you create a simple view with DDT enabled that passes the queryset as context then you will be able to see a breakdown of the repeated queries and exactly what is causing your slowdown. It's hard to tell from your example but I'm guessing the slowdown is because your filter is causing (at least) 3 queries for each object in participations_set

          – bdoubleu
          Nov 13 '18 at 17:52


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280047%2fquery-with-multiple-annotations-slows-down%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Full-time equivalent

          Bicuculline

          さくらももこ