Skip to main content
 首页 » 编程设计

python之如果索引超出范围(Python/Django),如何保存 None/Null

2024年10月24日34mengfanrong

我试图遍历对象列表并提取它们的属性并将它们添加到字典中。在此对象列表中,一些数据之前已填充,但有时会有空值或空白值。当循环遇到空白值时,它会抛出“索引超出范围”错误。

obj = Idea.objects.get(name=idea_name) 
new_obj = [] 
plan = ProductPlan.objects.all() 
for product in plan: 
    answers = product.question.answer_set.filter(idea=obj.id) 
    new_plan = {"title": product.title, "answer": answers[0]} 
    print new_plan 
    new_obj.append(new_plan) 
 
return render(request, 'idea.html', {"new_obj": new_obj, "obj":obj}) 

如果索引为空,我该如何将其存储为空。

请您参考如下方法:

answers = product.question.answer_set.filter(idea=obj.id) 
answer = answers[0] if answers.exists() else None 
new_plan = {"title": product.title, "answer": answer} 

以防万一您不知道,exists() 可以有效地测试查询集是否为空。检查django doc for more info .