Solved

Querying database objects based on foreign key in Django

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
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)

627 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