title: Django get count of nested related object
body: <p>I'm using <strong>Django 2.2</strong></p>
  
  <p>I have three models</p>
  
  <pre><code>class LeadList(SafeDeleteModel):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      name = models.CharField(max_length=128, verbose_name='Lead List Name')
  
      def entries_count(self):
          return LeadListEntry.objects.filter(
              dynamic_url_object__lead_list=self
          ).count()
  </code></pre>
  
  <pre><code>class DynamicUrlObject(SafeDeleteModel):
      lead_list = models.ForeignKey(
          LeadList,
          on_delete=models.SET_NULL,
          blank=True,
          null=True,
          default=None,
          related_name='dynamic_url_object'
      )
  </code></pre>
  
  <pre><code>class LeadListEntry(models.Model):
      dynamic_url_object = models.ForeignKey(
          'otherapp.DynamicUrlObject',
          on_delete=models.CASCADE,
          related_name='lead_list_entry'
      )
      data = models.TextField(help_text='Lead List entry data. (JSON data)', blank=False)
  </code></pre>
  
  <p><code>LeadList</code> has reference in the <code>DynamicUrlObject</code>.
  <code>LeadList</code> can be linked to multiple <code>DynamicUrlObject</code> instances.</p>
  
  <p>The <code>LeadListEntry</code> is linked to <code>DynamicUrlObject</code> to record data for each <code>DynamicUrlObject</code> instance.</p>
  
  <p>I want to get the <strong>count</strong> of <code>LeadListEntry</code> for particular <code>LeadList</code>.</p>
  
  <p>For that I have a model method in the <code>LeadList</code> model to return the count of the <code>LeadListEntry</code> entries.</p>
  
  <p>But on getting the list of <code>LeadList</code>, it is producing <strong>N+1</strong> problem where <code>entries_count</code> is called for each <code>lead_list</code> object which in turn runs a query on <code>LeadListEntry</code> to get the count.</p>
  
  <p>I tried to use <code>prefetch_related</code> in the view like</p>
  
  <pre><code>def get_queryset(self):
      return self.serializer_class.Meta.model.objects.filter(
          user=self.request.user
      ).prefetch_related(
          'dynamic_url_object__lead_list_entry'
      )
  </code></pre>
  
  <p>But there is no benefit of it.</p>
  
  <p><strong>How can I get the <code>count</code> for each <code>lead_list</code> object without running into <code>N+1</code> problem?</strong></p>