Helyx
Helyx

Reputation: 339

Error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

I'm trying to write an importer for a csv file. Here is a minimal example

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)
    <...some other stuff...>
    return



for row in dataReader:

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

    import_SO(st,"statename",row[3]) 

And here is my model

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

When I execute the code like it is, then I get the following error:

File "load_data.py", line 101, in <module>
    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.

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.

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

Any ideas?

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

to my code I get the following error:

Traceback (most recent call last):
  File "load_data.py", line 11, in <module>
    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

UPDATE: my installed apps:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myproject.myapp'
)

Upvotes: 0

Views: 4669

Answers (1)

Alasdair
Alasdair

Reputation: 308849

You need to call django.setup() in your script before you use the ORM to access data.

import django

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

django.setup()

See the docs for more info.

Upvotes: 2

Related Questions