簡體   English   中英

NameError:全局名稱“模型”未定義

[英]NameError: global name 'Model' is not defined

我有一個簡單的Django應用,我想在數據庫中定義兩個表: userquestion

我有以下models.py

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)

    @classmethod
    def create(cls, name):
        user = cls(name=name)
        return user


class Question(models.Model):
    content = models.CharField(max_length=300)
    answer = models.CharField(max_length=200)

    @classmethod
    def create(cls, content, answer):
        question = cls(content=content, answer=answer)
        return user

views.py定義的/questions中,我想顯示所有類型為question對象:

from django.views.generic.base import TemplateView
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.db import models


def questions(request):
    questions = Model.objects.raw('SELECT * FROM questions')
    return render_to_response('questions.html', questions)

但是,我得到:

NameError: global name 'Model' is not defined

為什么Model對象在models.py可見,而在views.py不可見?

另外,查詢數據庫的方式是否正確?

回答問題

Modelmodels.py 可見-它作為models.Model訪問。

您正在導入models但嘗試使用Model而不是models.Model

嘗試這個:

def questions(request):
    questions = models.Model.objects.raw('SELECT * FROM questions')
    return render_to_response('questions.html', questions)

或者,您可以直接導入Model

from django.db.models import Model

解決問題

我認為這是XY問題的一種情況。

您真正想要做的是訪問Question模型的所有實例。 如果出於某種原因要使用基於函數的視圖,則可以導入Question模型並直接與.all()

基於功能的視圖

問題/views.py

from myapp.models import Question

def questions(request):
    questions = Question.objects.all()
    return render_to_response('questions.html', questions)

基於類的視圖

但是,更好的選擇是使用基於類的通用視圖 文檔中的示例:

問題/views.py

from django.views.generic import ListView
from questions.models import Question

class QuestionList(ListView):
    model = Question

urls.py

from django.conf.urls import url
from questions.views import QuestionList

urlpatterns = [
    url(r'^questions/$', QuestionList.as_view()),
]

與基於功能的視圖相比,基於類的視圖提供了更大的表現力。 由於視圖的通常更改的部分可以單獨覆蓋(例如, get_context_data ),因此它們還消除了很多代碼重復的需求。

您必須通過以下方式在視圖內調用模型

from myapp.models import Question

def questions(request):
    questions = Question.objects.all()
    return render_to_response('questions.html', questions)

有關更多信息,請閱讀有關視圖的官方文檔... https://docs.djangoproject.com/en/1.10/topics/http/views/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM