How do I fix AttributeError: type object 'Book' has no attribute 'published_objects' on django_3.2

688 Views Asked by At

I am trying to create a custom model manager by modifying an already existing queryset. After adding the custom manager to my models.py file, models.py

from django.db import models
from django.db.models.fields import DateField
from django.utils import timezone, tree
from django.contrib.auth.models import User


class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
                self).get_queryset().filter(status='published')


class Book(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
 
    title = models.CharField(max_length=250)
    author = models.CharField(max_length=100)
    slug = models.SlugField(
        max_length=250, unique_for_date='uploaded_on')
    uploaded_by = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='book_posts')
    body = models.TextField()
    publish = models.DateField()
    uploaded_on = models.DateTimeField(default=timezone.now)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES, default='draft')

    objects = models.Manager()
    published_objects = PublishedManager()

    class Meta:
        ordering = ('-category', )

    def __str__(self):
        return self.title

If I use the python manage.py shell to test I was able to retrieve all books using

Book.objects.all()
>>> Book.objects.all()
<QuerySet [<Book: 48 Laws of Power>, <Book: The China Card>, <Book: Rich Dad, Poor Dad>]>```

But when trying to retrieve using my custom model, the is my following result

>>> Book.published_objects.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: type object 'Book' has no attribute 'published_objects'

How do I fix this error please, since i was following the original Django Documentations?

0

There are 0 best solutions below