Django loaddata 错误
我在应用程序目录下创建了一个“fixtures”文件夹,并把data1.json放在里面。
这个文件里包含了以下内容:
[{"firm_url": "http://www.graychase.com/kadam", "firm_name": "Gray & Chase", "first": " Karin ", "last": "Adam", "school": "Ernst Moritz Arndt University Greifswald", "year_graduated": " 2004"} ]
在命令行中,我切换到应用程序目录,然后
django-admin.py loaddata data1.json
但是我遇到了这个错误
Installing json fixture 'data1' from
'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures'.
Problem installing fixture
'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\data1.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 76, in Deserializer
Model = _get_model(d["model"])
KeyError: 'model'
我哪里做错了呢?
编辑:
我修正了json格式:
[
{
"pk": 1,
"model": "wkw2.Lawyer",
"fields": {
"school": "The George Washington University Law School",
"last": "Babas",
"firm_url": "http://www.graychase.com/babbas",
"year_graduated": "2005",
"firm_name": "Gray & Chase",
"first": "Amr A"
}
}
]
但是现在我得到了一个验证错误:这个值必须是一个整数。有没有办法通过行号找出是什么导致了这个错误?只有“pk”是一个整数。
Problem installing fixture 'C:\~\sw2\wkw2\fixtures\csvtest1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python_("This value must be an integer."))
ValidationError: This value must be an integer.
2 个回答
3
看起来问题出在你创建的这个数据文件上。以下几点可能会导致问题:
- 在创建数据文件后更改了数据库的结构,然后再把这个数据文件加载到新的结构中。
- 手动修改了数据文件的内容。
你是用 manage.py dumpdata
命令创建这个数据文件的吗?
12
看起来你没有正确地定义你的数据准备工具(fixtures)。可以看看这个Django文档。你需要先定义你要加载的模型,然后像这样定义字段:
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]