Reputation: 711
When I call the class from views.py, it doesn't call the function of the class. I am calling the function latest_question_list = Question.get_poll_question()
from views.py, but it doesn't print in my model function.
Here is my code:
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
Upvotes: 0
Views: 196
Reputation: 1024
You need to mark the method as classmethod
. Also using that global cursor
IMO is a very bad idea.
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()
Probably another best way of doing would be creating a model. If you don't control the table, you can create an unamanged Django model
Upvotes: 1