简体   繁体   English

在Django loaddata中,它会抛出json格式的错误但是对于yaml格式正常工作,为什么呢?

[英]In Django loaddata it throws errors for json format but work properly for yaml format, why?

In order to learn how to import initial data in database I created models as, 为了学习如何在数据库中导入初始数据我创建了模型,

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

after that, I use fixtures in .json format as given below, 之后,我使用.json格式的灯具,如下所示,

[
    {
        "model": "myapp.person",
        "pk": 1,
        "fields": {
            "first_name": "John",
            "last_name": "Lennon"
        }
    },
    {
        "model": "myapp.person",
        "pk": 2,
        "fields": {
            "first_name": "Paul",
            "last_name": "McCartney"
        }
    }
]

It throws error on loaddata 它会在loaddata上抛出错误

File "C:\Python27\lib\site-packages\django\core\serializers\python.py", line 96, in Deserializer

Model = _get_model(d["model"])

django.core.serializers.base.DeserializationError: Problem installing fixture 'I:\DJANGO\library\myapp\fixtures
\bookdata.json': string indices must be integers

But when I use fixture in YAML format as given below, 但是当我使用YAML格式的夹具时,如下所示,

- model: myapp.person
  pk: 1
  fields:
    first_name: John
    last_name: Lennon
- model: myapp.person
  pk: 2
  fields:
    first_name: Paul
    last_name: McCartney

It works like a charm. 它就像一个魅力。

Now I am confused what was wrong as whole things are just copied from their documentations. 现在我很困惑,因为整件事只是从他们的文件中复制出来。 I am using windows 32bit, Django 1.9, python 2.7. 我使用的是Windows 32bit,Django 1.9,python 2.7。

I've checked your code in linux mint/django 1.9/python 2.7 and it works fine. 我已经在linux mint / django 1.9 / python 2.7中检查了你的代码,它运行正常。

I think the problem may be the codification you have used in your files. 我认为问题可能是您在文件中使用的编码。 Please make sure that the json file uses UTF-8 codification and be careful not to use BOM . 请确保json文件使用UTF-8编码,并注意不要使用BOM Notepad++ editor can determine if the file includes a BOM and remove it. Notepad ++编辑器可以确定文件是否包含BOM并将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM