【问题标题】:Type error trying to load fixtures with Content_type natural keys in Django尝试在 Django 中使用 Content_type 自然键加载固定装置时出现类型错误
【发布时间】:2011-02-08 15:54:11
【问题描述】:

我在将我的一个模型转储到固定装置时使用 --natural 选项,这样我在部署时就不会遇到 Content_typ ID 问题。结果在这里:

{
     "pk": 1, 
     "model": "seo.opportunitymetadatamodel", 
     "fields": {
         "_content_type": [
              "opportunity", 
              "jobopportunity"
         ], 
         "og_description": "", 
         "description": "", 
         "title": "test", 
         "keywords": "", 
         "og_title": "", 
         "heading": ""
     }
}

但是当我尝试加载夹具时,我收到以下错误:

Problem installing fixture 'seo/fixtures/initial_data.json': Traceback (most recent call last):
  File "/Users/xx/dev/envs/xx/lib/python2.6/site-packages/django/core/management/commands/loaddata.py", line 167, in handle
    for obj in objects:
  File "/Users/xx/dev/envs/xx/lib/python2.6/site-packages/django/core/serializers/json.py", line 38, in Deserializer
    for obj in PythonDeserializer(simplejson.load(stream), **options):
  File "/Users/xx/dev/envs/xx/lib/python2.6/site-packages/django/core/serializers/python.py", line 84, in Deserializer
    Model = _get_model(d["model"])
TypeError: string indices must be integers, not str

似乎该方法不接受要加载的字符串。我错过了什么?

【问题讨论】:

    标签: python django fixtures


    【解决方案1】:

    我现在只能猜测,但是在查看了 Django 的源代码和您的错误消息之后,我认为您的夹具格式可能被破坏了。您发布的示例是文件的全部内容吗?如果是,那么我认为您需要将该模型放入列表中,如下所示(注意外括号):

    [
      {
        "pk": 1, 
        "model": "seo.opportunitymetadatamodel", 
        "fields": {
          "_content_type": [
            "opportunity", 
            "jobopportunity"
          ], 
          "og_description": "", 
          "description": "", 
          "title": "test", 
          "keywords": "", 
          "og_title": "", 
          "heading": ""
        }
      }
    ]
    

    为什么? Django 成功解析 JSON 数据后,将此数据传递给 python 反序列化器。这对数据进行如下迭代:

    82      for d in object_list:
    83          # Look up the model and starting build a dict of data for it.
    84          Model = _get_model(d["model"])
    

    http://code.djangoproject.com/browser/django/trunk/django/core/serializers/python.py#L82

    现在想象object_list 是一个json 对象(相当于python 的字典),迭代它只会得到键,在这种情况下pk, model, field。在第 84 行,Django 执行了_get_model(d["model"]),即使用字符串"model" 作为另一个字符串的索引,可能是pk(这是object_list 中的第一个元素)。这是一个类型错误。

    object_list 是一个实际列表时,迭代它会得到字典,可以用字符串索引。

    【讨论】:

    • lol.... 不知何故,我认为它来自自然密钥使用,因为这是我第一次使用它们。现在感觉很愚蠢;-)
    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 2012-09-16
    • 2017-10-27
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    相关资源
    最近更新 更多