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. 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.
我希望您在该文件中的其他位置重新分配名称MyModel
:您可能在某处有MyModel = 'whatever'
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.