[英]Django class based views, import inside get_queryset
I'm developing a small app, and I'm using class based views. 我正在开发一个小应用程序,我正在使用基于类的视图。 I was having an issue when implementing a very simple demonstrative search functionality, having the following error: 我在实现一个非常简单的演示搜索功能时遇到了问题,出现以下错误:
Exception Type: AttributeError
Exception Value: type object'MyModel' has no attribute 'objects'
I fixed this by including an import inside the get_queryset , although I had the import on the top of the file. 我通过在get_queryset中包含一个导入来解决这个问题 ,尽管我在文件的顶部有导入。 Find below a demonstrative piece of code: 在下面找到一段示范代码:
from mymodels.models import MyModel
class Search(generic.ListView):
"""Very simple search functionality."""
template_name = 'index.html'
context_object_name = 'object_list'
paginate_by = 5
def get_queryset(self):
from mymodels.models import MyModel
query = self.request.GET['search_text']
return MyModel.objects.filter(title__contains = query)
Does anyone know why this happens this way? 有谁知道为什么会这样发生? When I first did the Django tutorial using class based views, I didn't have this problem. 当我第一次使用基于类的视图完成Django教程时,我没有遇到这个问题。
我希望您在该文件中的其他位置重新分配名称MyModel
:您可能在某处有MyModel = 'whatever'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.