【问题标题】:Django string indices must be integers, not strDjango 字符串索引必须是整数,而不是 str
【发布时间】:2016-05-19 08:23:27
【问题描述】:

我使用表单创建 xml 请求并接收如下所示的 xml 响应:

<Root>
   <Header>
      <information>info</information>
   </Header>
   <Main>
      <Product>
         <Name>name1</Name>
         <Description>description1</Description>
         <Price>1</Price>
         <Pictures>
            <Picture>url_1</Picture>
            <Picture>url_2</Picture>
         </Pictures>
      </Product>
   </Main>
</Root>

然后使用此函数将 xml 数据转换为字典:

from xml.etree import cElementTree as ET
from collections import defaultdict

def etree_to_dict(t):
    d = {t.tag: {} if t.attrib else None}
    children = list(t)
    if children:
        dd = defaultdict(list)
        for dc in map(etree_to_dict, children):
            for k, v in dc.iteritems():
                dd[k].append(v)
        d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}}
    if t.attrib:
        d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems())
    if t.text:
        text = t.text.strip()
        if children or t.attrib:
            if text:
              d[t.tag]['#text'] = text
        else:
            d[t.tag] = text
    return d

e = ET.XML('''
<Root>
   <Header>
      <information>info</information>
   </Header>
   <Main>
      <Product>
         <Name>name1</Name>
         <Description>description1</Description>
         <Price>1</Price>
         <Pictures>
            <Picture>url_1</Picture>
            <Picture>url_2</Picture>
         </Pictures>
      </Product>
   </Main>
</Root>
''')

并将其存储到数据库中:

from pprint import pprint
d = etree_to_dict(e)

pprint(d)
d = etree_to_dict(e)

product = d['Root']['Main']['Product']
r = Product.objects.create()
r.name = product['Name']
r.description = product['Description']
r.price = product['Price']
r.save()

一切正常。但是当我尝试将图片保存到数据库时:

product_pictures=d['Root']['Main']['Pictures']
  for m in product_pictures:
    p = ProductPictures(
      picture = m['Picture']
    )
    p.product = r
    p.save()
    r.productpictures_set.all()

我在字符串 picture = m['Picture'] 上有 TypeError string indices must be integers, not str。 为什么会发生?我做错了什么。谢谢你的回答。

这是我的模型:

class Product(models.Model):
  name = models.CharField(max_length=200, blank=True, null=True)
  description = models.TextField(max_length=2000, blank=True, null=True)
  price = models.CharField(max_length=10, blank=True, null=True)

class ProductPictures(models.Model):
  product = models.ForeignKey(Product, null=True)
  picture = models.CharField(max_length=200, blank=True, null=True)

更新: 这是来自Local vars的数据:

product_pictures

{'Picture': [{'#text': 'http://images.static.goglobal.travel/images/hotels/67862/2010113161131438.jpg',
              '@Description': ''},
             {'#text': 'http://images.static.goglobal.travel/images/hotels/67862/2010113161132187.jpg',
              '@Description': ''},
             {'#text': 'http://images.static.goglobal.travel/images/hotels/67862/2010113161132406.jpg',
              '@Description': ''}]}

m

'Picture'
d

{'Root': {'Header': {'Information': '1521337'},
          'Main': {'Name': 'name1',
                   'Price': '1',
                   'Description': 'description',
                   'Pictures': {'Picture': [{'#text': 'http://images.static.goglobal.travel/images/hotels/67862/2010113161131438.jpg',
                                             '@Description': ''},
                                            {'#text': 'http://images.static.goglobal.travel/images/hotels/67862/2010113161132187.jpg',
                                             '@Description': ''},
                                            {'#text': 'http://images.static.goglobal.travel/images/hotels/67862/2010113161132406.jpg',
                                             '@Description': ''}]},
                   'RoomFacilities': None}}}

【问题讨论】:

  • m 似乎是一个字符串,而不是字典。虽然我无法弄清楚你在代码中的哪个位置将其设为字符串。
  • 请完整的错误堆栈
  • 你能打印出“d”字典的内容吗?
  • 我已经在更新我的帖子了
  • 我用“d”更新

标签: python django


【解决方案1】:

产品图片是一个对象/字典,只有一个图片键,因此迭代它没有意义。你可以遍历Picture

for m in product_pictures.get('Picture'):
    p = ProductPictures(
      picture = m.get('#text')
    )

虽然我怀疑树字典的创建存在问题,可能值得进一步调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    相关资源
    最近更新 更多