Home > Net >  Type object 'Book' has no attribute 'objects'
Type object 'Book' has no attribute 'objects'

Time:10-05

I am getting error AttributeError: type object 'Book' has no attribute 'objects' while running my django project.

Models.py

from django.db import models

# Create your models here.
"""Create or Save Model Instance. """
class BookManager(models.Manager):
  def create_book(self, title):
      book = self.create(title=title)
      return book

"""Book Model"""
class Book(models.Model):
  title = models.CharField(max_length=100, verbose_name="Book_Title")

  """Str Display. """
  def __str__(self):
      return self.title

  """To Save Model Instance. """
  object = BookManager()

views.py

from django.views import View
from .models import Book
from django.http import HttpResponse

# Create your views here.
"""Default View """
class default_view(View):
  def get(self, request):
     queryset=Book.objects.all()
     return HttpResponse(queryset)

  def post(self, request):
      # Getting Value of title
      title = request.POST.get('title')

      """Creating Book Instance. """
      book = Book(title=title)
      book.save()
      return HttpResponse('saved')

Error

Internal Server Error: /model_instance
Traceback (most recent call last):
  File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- 
  packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- 
  packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- 
  packages\django\views\generic\base.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- 
  packages\django\views\generic\base.py", line 142, in dispatch
    return handler(request, *args, **kwargs)
  File "D:\Concept_and_Project\Web Development\BackEnd\Django 
  Framework\Model\category\Model_Instance\Instance_method\views.py", line 9, in get
    queryset=Book.objects.all()
AttributeError: type object 'Book' has no attribute 'objects'
[04/Oct/2022 19:36:17] "GET /model_instance HTTP/1.1" 500 74725

CodePudding user response:

As @DavidSchultz also stated in above comment as:

probably because you write object = bookmanager(), instead of objects = bookmanager(), in your model definition.

By default manager is objects if you don't override.

You can do two things, one is to use, object as manager, so you should query using:

Book.object.all()

But it's recommended to use objects so you can simply change its name to objects from object, while overriding manager then query simply through:

Book.objects.all()
  • Related