Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Querying database objects based on foreign key in Django

Posted on 2014-11-23
2
Medium Priority
?
197 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 2000 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: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone 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

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…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
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…
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)
Suggested Courses

886 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