当我从views.py调用该类时,它没有调用该类的函数。我正在从views.py调用函数latest_question_list = Question.get_poll_question()
,但未在模型函数中打印。
这是我的代码:
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Choice, Question
from django.urls import reverse
from django.shortcuts import get_object_or_404, render
def index(request):
latest_question_list = Question.get_poll_question()
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
models.py
import datetime
from django.utils import timezone
from django.db import connection
global cursor
cursor = connection.cursor()
class Question():
print(123)
def get_poll_question():
print(456)
db_table = "polls_question"
cursor.execute('SELECT * FROM '+db_table)
return allquestions
class Choice():
def __str__(self):
db_table = "polls_choice"
cursor.execute("SELECT * FROM "+ db_table+" WHERE question_id = '1' ")
choice_text = cursor.fetchall();
return self.choice_text
答案 0 :(得分:1)
您需要将方法标记为classmethod
。也使用该全局游标
IMO是一个非常糟糕的主意。
https://docs.djangoproject.com/en/2.2/topics/db/sql/#executing-custom-sql-directly
class Question:
@classmethod
def get_poll_question(cls):
with connection.cursor() as cursor:
db_table = "polls_question"
cursor.execute(f"SELECT * FROM {db_table}")
return cursor.fetchall()
可能的另一种最佳执行方式是创建模型。如果你不这样做 控制表格,您可以创建一个unamanged Django model