функция не получает вызов из класса из файла представления в Python - PullRequest
0 голосов
/ 25 апреля 2019

Когда я вызываю класс из views.py, он не вызывает функцию класса.Я вызываю функцию latest_question_list = Question.get_poll_question() из views.py, но она не печатается в моей модели.

Вот мой код:

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

1 Ответ

1 голос
/ 25 апреля 2019

Вам необходимо пометить метод как 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()

Вероятно, еще один лучший способ сделать это - создать модель.Если вы не управляете таблицей, вы можете создать неуправляемую модель Django

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...