Solved

Querying database objects based on foreign key in Django

Posted on 2014-11-23
2
184 Views
Last Modified: 2014-11-25
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!
0
Comment
Question by:Errang Genevre
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
ID: 40461526
The choices for a question are retrieved through a question's choice_set property.

There's really no reason to pass in a dictionary.  You'd typically do something more like this:
views.py
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    return render(request, 'polls/index.html', {'latest_question_list': latest_question_list })

Open in new window

index.html
{% if latest_question_list %}
	{% for question in latest_question_list %}
        <p>{{ question }}</p>
            <ul>
            {% for choice in question.choice_set.all %}
                <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


But if you want it in a dictionary that works with your posted template, then:
views.py
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    question_dictionary = dict([ (q, q.choice_set.all()) for q in latest_question_list ])
    return render(request, 'polls/index.html', {'question_dictionary': question_dictionary })

Open in new window

0
 

Author Closing Comment

by:Errang Genevre
ID: 40466030
Thanks a lot!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question