3

I trying to loop through a list of objects and pull out their attributes and add them to a dictionary. In this list of objects some of the data was previously populated but sometimes there will be null or blank values. When the loop runs into the blank value it throws an "Index out of Range" Error.

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})

If the index is null, how do I just store it as empty.

1 Answer 1

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

Just in case you don't know, exists() would efficiently test whether a queryset is empty or not. Check django doc for more info.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.