python - 如何修复 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 文档?
解决方案
推荐阅读
- chrome-web-store - Chrome 扩展打开多个标签
- machine-learning - 什么是用来训练自注意力机制的?
- java - 为什么异常日志会使用相同的代码更改打印位置?
- python - 魔术方法 __str__ 不调用 str 调用
- python - 从在线 xml 中获取价值
- scala - 在 EMR 环境中向 Spark 提交 JAR 时出现 FileNotFoundException (stderr & stdout)
- java - 麻烦在 MacOS Mojave 上安装 pymssql
- typescript - 如何防止使用 TypeScript 在构造函数中未定义成员?
- caching - 处理 Redis 缓存存储断开连接上的 Nest.js 应用
- javascript - 乘法循环不相乘