Python 3.x 索引器错误:Django Python应用程序中的列表索引超出范围

Python 3.x 索引器错误:Django Python应用程序中的列表索引超出范围,python-3.x,django-views,Python 3.x,Django Views,我对一个数组有迭代的函数有一个问题。这是我的职责 def create_new_product(): tree = ET.parse('products.xml') root = tree.getroot() array = [] appointments = root.getchildren() for appointment in appointments: appt_children = appointment.getchildr

我对一个数组有迭代的函数有一个问题。这是我的职责

def create_new_product():
    tree = ET.parse('products.xml')
    root = tree.getroot()

    array = []

    appointments = root.getchildren()
    for appointment in appointments:
        appt_children = appointment.getchildren()

        array.clear()

        for appt_child in appt_children:
            temp = appt_child.text
            array.append(temp)

        new_product = Product(
                product_name = array[0],
                product_desc = array[1]
        )
        new_product.save()

    return new_product
当我调用该函数时,它将两个产品保存到数据库中,但在第三个产品上出现错误。这就是错误

    product_name = array[0],
IndexError: list index out of range
这也是xml文件。我只从xml复制了前3个产品。xml文件中几乎有2700种产品

<?xml version="1.0" encoding="UTF-8"?>
<Products>
  <Product>
    <product_name>Example 1</product_name>
    <product_desc>EX101</product_desc>
  </Product>
  <Product>
    <product_name>Example 2</product_name>
    <product_desc>EX102</product_desc>
  </Product>
  <Product>
    <product_name>Example 3</product_name>
  </Product>
</Products>

例1
EX101
例2
EX102
例3

我不明白为什么会出现这个错误,因为它已经适用于xml文件中的前两个产品

仅当数组中的某个位置无效时才会抛出超出范围的列表索引,因此产品名称[0]实际上不存在。也许可以尝试发布您的XML文件,我们将查看是否有错误。

我已经在python 3上运行了您的代码的最低版本(我假设它是3,因为您使用了
array.clear()
):

输出:

{'product_name': 'Example 1', 'product_desc': 'EX101'}
{'product_name': 'Example 2', 'product_desc': 'EX102'}
Warning : skipping element since it has less children than 2

编辑:OP发现产品包含的子项有时比预期的少。我添加了元素编号的检查。

你能发布xml文件吗?我添加了xml文件@MadjaoueCo你能试试我发布的代码并告诉我你是否得到了与所示相同的输出吗?我添加了xml文件我意识到问题来自xml文件。我的意思是每个产品通常有27个字段,但我发现其中一些有25个字段。这就是为什么我会出错。现在,一切都好了。我将编辑我的问题以显示此错误,然后如果您相应地更改您的答案,我将为其他用户接受它,以便他们能够理解为什么会发生这种情况。我编辑了我的帖子,当孩子的数量与你期望的不同时,它会发出警告。
{'product_name': 'Example 1', 'product_desc': 'EX101'}
{'product_name': 'Example 2', 'product_desc': 'EX102'}
Warning : skipping element since it has less children than 2