title: How to fix "InternalError: variable not found in subplan target list"
body: <p>I have a legacy Django project (django-1.1.29) and some tests in pytest (pytest-4.3.0), all running inside Docker. The database is PostgreSQL 10 and is a docker-compose service on which the application depends on. The python version is 2.7.18.</p>
  <p>Lately the tests started to fail with a strange error:</p>
  <p><code>InternalError: variable not found in subplan target list</code>.</p>
  <p>The error occurs only when I count the number of objects of a certain model, e.g. <code>Problem.objects.count()</code>. The instruction is turned into the following query</p>
  <p><code>(0.000) SELECT COUNT(*) AS &quot;__count&quot; FROM &quot;problems_problem&quot;; args=() </code> by Django.</p>
  <p>The whole log is here:</p>
  <pre><code>self = &lt;integration_tests.project_name.subjects.test_views.test_theme_problem_view_set.TestThemeProblemViewSet object at 0x7f01faccbe50&gt;
  jclient = &lt;project_name.common.test_utils.json_client.JSONClient object at 0x7f01fadb8ed0&gt;
  
      def test_all_is_ok(self, jclient, subject_model, content_manager):
          url, data = self._main_prepare(jclient, subject_model, content_manager)
          response = jclient.post_json(url, data[0])
          assert response.status_code == 201
  &gt;       assert Problem.objects.count() == 1
  
  integration_tests/project_name/subjects/test_views/test_theme_problem_view_set.py:86: 
  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
  /usr/local/lib/python2.7/dist-packages/django/db/models/manager.py:85: in manager_method
      return getattr(self.get_queryset(), name)(*args, **kwargs)
  /usr/local/lib/python2.7/dist-packages/django/db/models/query.py:364: in count
      return self.query.get_count(using=self.db)
  /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py:499: in get_count
      number = obj.get_aggregation(using, ['__count'])['__count']
  /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py:480: in get_aggregation
      result = compiler.execute_sql(SINGLE)
  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
  
  self = &lt;django.db.models.sql.compiler.SQLCompiler object at 0x7f01faee3a50&gt;
  result_type = 'single', chunked_fetch = False
  
      def execute_sql(self, result_type=MULTI, chunked_fetch=False):
          &quot;&quot;&quot;
          Run the query against the database and returns the result(s). The
          return value is a single data item if result_type is SINGLE, or an
          iterator over the results if the result_type is MULTI.
      
          result_type is either MULTI (use fetchmany() to retrieve all rows),
          SINGLE (only retrieve a single row), or None. In this last case, the
          cursor is returned if any query is executed, since it's used by
          subclasses such as InsertQuery). It's possible, however, that no query
          is needed, as the filters describe an empty set. In that case, None is
          returned, to avoid any unnecessary database interaction.
          &quot;&quot;&quot;
          if not result_type:
              result_type = NO_RESULTS
          try:
              sql, params = self.as_sql()
              if not sql:
                  raise EmptyResultSet
          except EmptyResultSet:
              if result_type == MULTI:
                  return iter([])
              else:
                  return
          if chunked_fetch:
              cursor = self.connection.chunked_cursor()
          else:
              cursor = self.connection.cursor()
          try:
              cursor.execute(sql, params)
          except Exception as original_exception:
              try:
                  # Might fail for server-side cursors (e.g. connection closed)
                  cursor.close()
              except Exception:
                  # Ignore clean up errors and raise the original error instead.
                  # Python 2 doesn't chain exceptions. Remove this error
                  # silencing when dropping Python 2 compatibility.
                  pass
  &gt;           raise original_exception
  E           InternalError: variable not found in subplan target list
  
  /usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py:899: InternalError
  </code></pre>
  <p>I would really appreciate if anyone could help me fix this issue or at least give some hints where to find the reasons.</p>
  <p>Here is what I've attempted to do so far but none of these helped:</p>
  <ul>
  <li>Use different versions of PostgreSQL (10, 11, 12, 13)</li>
  <li>Disable the server-side cursor</li>
  </ul>