Solved

Querying database objects based on foreign key in Django

Posted on 2014-11-23
2
177 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
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

746 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now