Link to home
Start Free TrialLog in
Avatar of Errang Genevre
Errang Genevre

asked on

Querying database objects based on foreign key in Django

Hello,

I'm relatively new to Django, and I'm trying to modify the Django tutorial (https://docs.djangoproject.com/en/1.7/intro/tutorial04/)a little bit.

What I'm trying to do is get the votes and the questions on the same page.

Now, I know that I can get dictionaries to work; because I got this to work:

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]

    question_dictionary = {}

    question_dictionary[latest_question_list[0]] = ['test', 'a', 'b', 'c']

    context = {'question_dictionary': question_dictionary}
    return render(request, 'quizzes/index.html', context)

index.html:
% if question_dictionary %}
        {% for question, choices in question_dictionary.items %}
        <p>{{ question }}</p>
            <ul>
            {% for choice in choices %}
                <input type="radio" name="choice" id="choice {{ forloop.counter }}" value="{{ choice.id }}" />
                <label for="choice {{ forloop.counter }}">{{ choice }}</label><br />
            {% endfor %}
            </ul>
        {% endfor %}
{% else %}
        <p>No questions are available.</p>
{% endif %}

Open in new window


But the following code doesn't work; is there some simple thing in Django I'm missing?

views.py:
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')

    question_dictionary = {}

    for question in latest_question_list:
        question_dictionary[question.question_text] = question_dictionary.get(question.question_text, [])
        if not question_dictionary[question.question_text]:
            temp_list = get_object_or_404(question.question_text, pk=question.pk)
            question_dictionary[question.question_text] = temp_list

index.html:
{% if question_dictionary %}
        {% for question, choices in question_dictionary.items %}
        <p>{{ question }}</p>
            <ul>
            {% for choice in choices %}
                <input type="radio" name="choice" id="choice {{ forloop.counter }}" value="{{ choice.id }}" />
                <label for="choice {{ forloop.counter }}">{{ choice.choice_text }}</label><br />
            {% endfor %}
            </ul>
        {% endfor %}
{% else %}
        <p>No questions are available.</p>
{% endif %}

Open in new window


Appreciate any help!
ASKER CERTIFIED SOLUTION
Avatar of clockwatcher
clockwatcher

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Errang Genevre
Errang Genevre

ASKER

Thanks a lot!