Error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
<p>I'm trying to write an importer for a csv file. Here is a minimal example</p>

<pre><code>csv_filepathname="/home/thomas/Downloads/zip.csv"
your_djangoproject_home="~/Desktop/Projects/myproject/myproject/"

import sys,os,csv

sys.path.append(your_djangoproject_home)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.db.models.fields.related import ManyToManyField
from myapp.models import ZipCode,state


dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')




def import_SO(item, crit,val):

    debug = 1;

    obj_state=type(item).objects.filter(crit=val)
    &lt;...some other stuff...&gt;
    return



for row in dataReader:

    st=state(statecode=row[2],statename=row[3])

    import_SO(st,"statename",row[3]) 
</code></pre>

<p>And here is my model</p>

<pre><code>class state(models.Model):
    statecode = models.CharField(max_length=2, default='XX')
    statename = models.CharField(max_length=32, default='XXXXXXXXXXXXX')
</code></pre>

<p>When I execute the code like it is, then I get the following error:</p>

<pre><code>File "load_data.py", line 101, in &lt;module&gt;
    import_SO(st,"statename",row[3]) # Objekt, Kriterium, zu vergleichender Wert
  File "load_data.py", line 68, in import_SO
    obj_state=type(item).objects.filter(crit=val)#crit=val) # suche object mit merkmal, hier statename
  File "/usr/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 679, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 697, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1310, in add_q
    clause, require_inner = self._add_q(where_part, self.used_aliases)
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1338, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1150, in build_filter
    lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1036, in solve_lookup_type
    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1394, in names_to_path
    field_names = list(get_field_names_from_opts(opts))
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 45, in get_field_names_from_opts
    for f in opts.get_fields()
  File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 740, in get_fields
    return self._get_fields(include_parents=include_parents, include_hidden=include_hidden)
  File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 802, in _get_fields
    all_fields = self._relation_tree
  File "/usr/lib/python2.7/dist-packages/django/utils/functional.py", line 59, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 709, in _relation_tree
    return self._populate_directed_relation_graph()
  File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 681, in _populate_directed_relation_graph
    all_models = self.apps.get_models(include_auto_created=True)
  File "/usr/lib/python2.7/dist-packages/django/utils/lru_cache.py", line 101, in wrapper
    result = user_function(*args, **kwds)
  File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 168, in get_models
    self.check_models_ready()
  File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 131, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
</code></pre>

<p>But when i change the line "obj_state=type(item).objects.filter(crit=val)" to "obj_state=type(item).objects.filter(statename=val)"
then everything works fine. So there seems to be a problem with the variable "crit" whicht stands for the searchcriteria, in this example "statename". So I want to pass the crit via arguments to the method "import_SO" but for some reason it doesn't work.</p>

<p>When I print the variable crit right before the error occurs, the content of the variable seems to be correct.</p>

<p>Any ideas?</p>

<p>Update:
after adding
<code>your_djangoproject_home="~/Desktop/Projects/myproject</code> and <code>os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'</code></p>

<p>to my code I get the following error:</p>

<pre><code>Traceback (most recent call last):
  File "load_data.py", line 11, in &lt;module&gt;
    django.setup()
  File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/usr/lib/python2.7/dist-packages/django/apps/config.py", line 112, in create
    mod = import_module(mod_path)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named myproject
</code></pre>

<p>UPDATE:
my installed apps:</p>

<pre><code>INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myproject.myapp'
)
</code></pre>

<p>You need to call <code>django.setup()</code> in your script before you use the ORM to access data.</p>

<pre><code>import django

sys.path.append(your_djangoproject_home)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

django.setup()
</code></pre>

<p>See <a href="https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage" rel="nofollow">the docs</a> for more info.</p>

python django