[英]NameError: global name 'Model' is not defined
我有一個簡單的Django應用,我想在數據庫中定義兩個表: user
和question
。
我有以下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
不可見?
另外,查詢數據庫的方式是否正確?
Model
在models.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()
:
from myapp.models import Question
def questions(request):
questions = Question.objects.all()
return render_to_response('questions.html', questions)
from django.views.generic import ListView
from questions.models import Question
class QuestionList(ListView):
model = Question
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.