rmcc
rmcc

Reputation: 783

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. 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.

Upvotes: 0

Views: 201

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

I expect that you reassign the name MyModel somewhere else in that file: you probably have MyModel = 'whatever' somewhere.

Upvotes: 2

Related Questions