Python Django字符串索引必须是整数,而不是str
使用表单i创建xml请求并接收xml响应,如下所示:Python Django字符串索引必须是整数,而不是str,python,django,Python,Django,使用表单i创建xml请求并接收xml响应,如下所示: <Root> <Header> <information>info</information> </Header> <Main> <Product> <Name>name1</Name> <Description>description1</
<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()
我得到了TypeError
字符串索引必须是整数,而不是字符串picture=m['picture']
上的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)
UPD:
以下是来自本地变量的数据:
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}}}
Product pictures是一个对象/字典,只有一个图片键,因此对其进行迭代是没有意义的。您可以在图片上迭代
for m in product_pictures.get('Picture'):
p = ProductPictures(
picture = m.get('#text')
)
尽管我怀疑树dict的创建中存在一个值得进一步调试的问题。m
似乎是一个字符串,而不是一个字典。虽然我不知道你在代码中的什么地方把它变成了字符串。完整的错误堆栈请你打印出“d”字典的内容好吗?我正在用“d”更新我的帖子
for m in product_pictures.get('Picture'):
p = ProductPictures(
picture = m.get('#text')
)