title: django filtering querysets causes 'AppRegistryNotReady: Models aren't loaded yet.' with forms within models.py
body: <p>During the development of our current django-project (django 1.7.1) we reach the task to mark some database-entries as deleted and remove them from user's sight but not completely from db.</p>
  <p>A fast straightforward solution I found <a href="https://github.com/paltman/django-logicaldelete" rel="nofollow noreferrer">django-logicaldelete</a> (exactly what we want to do!)</p>
  <p>Following the instruction from django-logicaldelete I installed logicaldelete with pip and added it as INSTALLED_APP to settings.py</p>
  <p>Only thing left was to add logicaldelete in models.py and admin.py an inherit from it</p>
  <pre><code>...
  import logicaldelete
  
  class MyModel(logicaldelete.models.Model){...}
  ... 
  </code></pre>
  <hr />
  <pre><code>...
  import logicaldelete
      
  class MyModelAdmin(logicaldelete.admin.ModelAdmin){...}
  ... 
  </code></pre>
  <p>So far so good :)
  Trying to run the project now causes an 'AppRegistryNotReady: Models aren't loaded yet.' - Error:</p>
  <pre><code>    Traceback (most recent call last):
        File &quot;C:\Python34\lib\site-packages\django\db\models\options.py&quot;, line 414, in get_field_by_name
          return self._name_map[name]
      AttributeError: 'Options' object has no attribute '_name_map'
  
  During handling of the above exception, another exception occurred:
  
  Traceback (most recent call last):
    File &quot;C:\Python34\lib\site-packages\django\db\models\options.py&quot;, line 561, in get_all_related_m2m_objects_with_model
      cache = self._related_many_to_many_cache
  AttributeError: 'Options' object has no attribute '_related_many_to_many_cache'
  
  During handling of the above exception, another exception occurred:
  
      Traceback (most recent call last):
        File &quot;C:\eclipse\workspacePraxis\promotionsdatenbank\manage.py&quot;, line 10, in &lt;module&gt;
          execute_from_command_line(sys.argv)
        File &quot;C:\Python34\lib\site-packages\django\core\management\__init__.py&quot;, line 385, in execute_from_command_line
          utility.execute()
        File &quot;C:\Python34\lib\site-packages\django\core\management\__init__.py&quot;, line 354, in execute
          django.setup()
        File &quot;C:\Python34\lib\site-packages\django\__init__.py&quot;, line 21, in setup
          apps.populate(settings.INSTALLED_APPS)
        File &quot;C:\Python34\lib\site-packages\django\apps\registry.py&quot;, line 108, in populate
          app_config.import_models(all_models)
        File &quot;C:\Python34\lib\site-packages\django\apps\config.py&quot;, line 202, in import_models
          self.models_module = import_module(models_module_name)
        File &quot;C:\Python34\lib\importlib\__init__.py&quot;, line 109, in import_module
          return _bootstrap._gcd_import(name[level:], package, level)
        File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 2254, in _gcd_import
        File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 2237, in _find_and_load
        File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 2226, in _find_and_load_unlocked
        File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1200, in _load_unlocked
        File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1129, in _exec
        File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1471, in exec_module
        File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 321, in _call_with_frames_removed
        File &quot;C:\eclipse\workspacePraxis\promotionsdatenbank\personen\models.py&quot;, line 144, in &lt;module&gt;
          class PromovendChoice(forms.Form):
        File &quot;C:\eclipse\workspacePraxis\promotionsdatenbank\personen\models.py&quot;, line 149, in PromovendChoice
          promovend_choice = forms.ModelChoiceField(queryset=Promovend.objects.all(), to_field_name='nachname', empty_label=&quot;Promovend&quot;)
        File &quot;C:\Python34\lib\site-packages\django\db\models\manager.py&quot;, line 191, in all
          return self.get_queryset()
        File &quot;C:\Python34\lib\site-packages\logicaldelete\managers.py&quot;, line 15, in get_queryset
          return LogicalDeleteQuerySet(self.model, using=self._db).filter(date_removed__isnull=True)
        File &quot;C:\Python34\lib\site-packages\django\db\models\query.py&quot;, line 691, in filter
          return self._filter_or_exclude(False, *args, **kwargs)
        File &quot;C:\Python34\lib\site-packages\django\db\models\query.py&quot;, line 709, in _filter_or_exclude
          clone.query.add_q(Q(*args, **kwargs))
        File &quot;C:\Python34\lib\site-packages\django\db\models\sql\query.py&quot;, line 1287, in add_q
          clause, require_inner = self._add_q(where_part, self.used_aliases)
        File &quot;C:\Python34\lib\site-packages\django\db\models\sql\query.py&quot;, line 1314, in _add_q
          current_negated=current_negated, connector=connector)
        File &quot;C:\Python34\lib\site-packages\django\db\models\sql\query.py&quot;, line 1138, in build_filter
          lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
        File &quot;C:\Python34\lib\site-packages\django\db\models\sql\query.py&quot;, line 1076, in solve_lookup_type
          _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        File &quot;C:\Python34\lib\site-packages\django\db\models\sql\query.py&quot;, line 1339, in names_to_path
          field, model, direct, m2m = opts.get_field_by_name(name)
        File &quot;C:\Python34\lib\site-packages\django\db\models\options.py&quot;, line 416, in get_field_by_name
          cache = self.init_name_map()
        File &quot;C:\Python34\lib\site-packages\django\db\models\options.py&quot;, line 445, in init_name_map
          for f, model in self.get_all_related_m2m_objects_with_model():
        File &quot;C:\Python34\lib\site-packages\django\db\models\options.py&quot;, line 563, in get_all_related_m2m_objects_with_model
          cache = self._fill_related_many_to_many_cache()
        File &quot;C:\Python34\lib\site-packages\django\db\models\options.py&quot;, line 577, in _fill_related_many_to_many_cache
          for klass in self.apps.get_models():
        File &quot;C:\Python34\lib\functools.py&quot;, line 428, in wrapper
          result = user_function(*args, **kwds)
        File &quot;C:\Python34\lib\site-packages\django\apps\registry.py&quot;, line 168, in get_models
          self.check_models_ready()
        File &quot;C:\Python34\lib\site-packages\django\apps\registry.py&quot;, line 131, in check_models_ready
          raise AppRegistryNotReady(&quot;Models aren't loaded yet.&quot;)
      django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
  </code></pre>
  <p>I read about that problem since django 1.7 and as solution</p>
  <pre><code>import django
  django.setup()
  </code></pre>
  <p>is given. Here I doesn't work to add those lines.
  Tried to add it in logicaldelete.managers.py and logicaldelete.query.py</p>
  <p>Seems I've got the wrong Idea what causes the problem.</p>
  <p>The only part of my own code shown in the errors' traceback ist this call within a form:</p>
  <pre><code>promovend_choice = forms.ModelChoiceField(queryset=Promovend.objects.all(), to_field_name='nachname', empty_label=&quot;Promovend&quot;)
  </code></pre>
  <p>Hope you know a way to solve this...</p>
  <p>If not I'll just override the delete-method and add a manager on my own.</p>
  <h1><strong>Update no. 3</strong></h1>
  <p>I've implemented a BaseModel and a suitable Manager on my own (it hardly differs from logicaldelete)</p>
  <pre><code>class SoftDeleteBaseModel(models.Model):
  
      deleted = models.BooleanField(default=False)
      
      objects = SoftDeleteManager(False)
      objects_deleted = SoftDeleteManager(True)
      all_objects = models.Manager()
      
      def delete(self):
          related_models = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()]
          
          for model_objects in rleated_models:
              related_objects = getattr(self, model_objects).all()
  
              for related_object in related_objects:
                  if not issubclass(related_object.__class__, SoftDeleteBaseModel):  
                      break
                  related_object.delete()
          
          self.deleted= True
          self.save()
          
      class Meta:
          abstract = True
  </code></pre>
  <hr />
  <pre><code>class SoftDeleteManager(models.Manager):
      
      def __init__(self, show_deleted=False):
          super(SoftDeleteManager, self).__init__()
          self.show_deleted = show_deleted
           
      def get_queryset(self):
          qs = super(SoftDeleteManager, self).get_queryset()
          return qs.filter(deleted=self.show_deleted)
  </code></pre>
  <p>Unfortunately the same error occurs. Importing <em>django</em> an calling <em>django.setup()</em> in my managers.py file doesn't work either.</p>
  <p>There is some problem calling the (self-made) manager with</p>
  <pre><code>objects = SoftDeleteManager(False)
  objects_deleted = SoftDeleteManager(True)
  all_objects = models.Manager()
  </code></pre>
  <p>Seems the SoftDeleteManger isn't ready (loaded) while my Model wants to refer to it..</p>
  <h1>Update no. 4</h1>
  <p>New findings:</p>
  <p>Suggesting the error lies within my form wasn't that bad! I wondered using <code>queryset = model.objects.all()</code> with standard-manager works fine, replacing it with my <strong>SoftDeleteManager</strong> causes an error...</p>
  <p>The idea came up: Why not adding a filter to that codeline using standard-manager?
  <code>queryset = models.objects.all().filter(deleted=False)</code>
  That code causes the AppRegistryNotReady-error as well - so the root cause seems to be filtering the querysets within my self-made Manager...</p>
  <h3>Edit</h3>
  <p>I found a similiar problem with filtering querysets <a href="https://stackoverflow.com/questions/25353959/django-filter-query-doesnt-work">here</a>.
  But as mentioned at the top I tried using <code>import django</code> and <code>django.setup()</code> without success...</p>
  <h1>Update no. 5</h1>
  <p>After reading a hundred times calling <code>django.setup()</code> would solve the problem I called it within my <em>models.py</em>, expecting the an error or a successful run... but nothing happens at all. Running the project creates a python-process but there is no output neither the development server starts...</p>
  <p>Greetings,
  Tobi</p>