当前位置: 动力学知识库 > 问答 > 编程问答 >

django - Chartit Module how to get the foreign key

问题描述:

I want to make a chart using the Polls example used on Django Doc. My problem is that I want to do it with each question. As of now I can show a pie chart with one question, but I realize that I am using one question.choice and the ids of the choices. But if I wan to use one question I cannot us id as one my arguments because it is going to get the question.id, not the choice.id. It is not easy for me to explain as clear.

Here is my code

def vote_results(request):

#datapool with the data we want to retrieve

votedata = DataPool(series=[{'options': {

'source': Choice.objects.all()},

'terms': [

'id',

'votes']}

])

#Create chart object

cht = Chart(

datasource=votedata,

series_options =

[{'options':{

'type': 'pie',

'stacking': False},

'terms':{

'id': [

'votes']

}}],

chart_options =

{'title': {

'text': 'What team will win NBA champ?' }},

x_sortf_mapf_mts = (None, monthname, False))

#Send the chart object to the template

return render_to_response('polls/votes.html', {'votesdata': cht})

My question is how do I use the Question.objects.all() to get the question, but also use the Choice for each question, so that when a user vote for a question, he can see the results for that question's choices? If I do that now I will show all the choices of all the questions.

Do you see what I am trying to ask?

网友答案:

I don't really understand what you want to do, but i try to help. So we have two models:

class Question(models.Model):
  question_text = models.CharField(max_length=200)
  pub_date = models.DateTimeField('date published')


class Choice(models.Model):
  question = models.ForeignKey(Question, on_delete=models.CASCADE)
  choice_text = models.CharField(max_length=200)
  votes = models.IntegerField(default=0)

if you want to get all questions with choices on it, you have to make this request:

questions = Qustions.objects.all()

then in template should look something like this:

{% for question in questions %}
   <p>{{question.question_text}}</p>
   {% for choice in qustion.choice_set.all %}
      {{choiceschoice_text}}
   {% endfor%}
{% endfor %}

hope it helps you

分享给朋友:
您可能感兴趣的文章:
随机阅读: