django中的数据库查询

时间:2015-09-30 19:07:12

标签: python django

我正在使用django创建一个简单的测验应用。当用户提交问题的答案时,将使用数据库中存在的正确答案检查答案。

views.py

from django.shortcuts import render,get_object_or_404
from .models import question
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse

def detail(request, question_id):
    ques = get_object_or_404(question, pk=question_id)
    return render(request, 'detail.html', {'ques': ques})

def index(request):
    questions = question.objects.all()
    return render(request,"question.html",{"questions":questions})

def vote(request,question_id):
    p = get_object_or_404(question, pk=question_id)
    selected_choice = p.choice_set.get(pk = request.POST['choice'])
    print selected_choice,p.answer_text
    if(selected_choice == p.answer_text):
        print "yes"
    x = int(question_id) + 1
    return HttpResponseRedirect(reverse('detail', args=(str(x))))

在用户点击提交按钮后调用投票功能。检查在这里进行。当我打印selected_choice和p.answer_text时,它们会显示正确的值。但是当我使用相等运算符比较它们时,即使它们都相同,它也不会返回true。

models.py
    from django.db import models

    class question(models.Model):
        question_text = models.CharField(max_length = 400)
        answer_text = models.CharField(max_length = 400,default = "name")
        def __unicode__(self):
            return self.question_text,self.answer_text
    class choice(models.Model):
        question = models.ForeignKey(question)
        choice_text = models.CharField(max_length = 200)
        def __unicode__(self):
            return self.choice_text

0 个答案:

没有答案