我正在尝试为csv文件编写导入程序。这是一个最小的例子
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])
这是我的模特
class state(models.Model):
statecode = models.CharField(max_length=2, default='XX')
statename = models.CharField(max_length=32, default='XXXXXXXXXXXXX')
当我执行代码时,我收到以下错误:
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.
但是当我将“obj_state = type(item).objects.filter(crit = val)”更改为“obj_state = type(item).objects.filter(statename = val)”时 一切正常。所以似乎存在变量“crit”的问题,它代表searchcriteria,在这个例子中是“statename”。所以我想通过参数将暴击传递给方法“import_SO”但由于某种原因它不起作用。
当我在错误发生之前打印变量crit时,变量的内容似乎是正确的。
有什么想法吗?
更新:
添加后
your_djangoproject_home="~/Desktop/Projects/myproject
和os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
到我的代码我收到以下错误:
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
更新: 我安装的应用程序:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myproject.myapp'
)
答案 0 :(得分:2)
在使用ORM访问数据之前,您需要在脚本中调用django.setup()
。
import django
sys.path.append(your_djangoproject_home)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
django.setup()
有关详细信息,请参阅the docs。