gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:23 25 4
gpt4 key购买 nike

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

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 .

关于python - 如果索引超出范围(Python/Django),如何保存 None/Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35491134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com