首页 > 解决方案 > 如何修复 AttributeError: type object 'Book' has no attribute 'published_objects' on django_3.2

问题描述

我正在尝试通过修改已经存在的查询集来创建自定义模型管理器。将自定义管理器添加到我的 models.py 文件之后, 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

如果我使用 python manage.py shell 进行测试,我能够使用检索所有书籍

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

但是当尝试使用我的自定义模型进行检索时,这是我的以下结果

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

请问我该如何解决这个错误,因为我正在关注原始的 Django 文档?

标签: pythondjangodjango-modelsdjango-querysetdjango-custom-manager

解决方案


推荐阅读