You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django 1.10报错‘Manager isn't accessible via Post instances’求助

Fixing the "Manager isn't accessible via Post instances" Error in Django 1.10

What's Causing This Error?

This error pops up when you try to access a manager (like your PublishedManager) from an instance of your Post model, instead of accessing it directly from the Post class itself. Managers are meant to be attached to model classes, not individual objects. Also, it looks like you've defined the custom manager but haven't registered it with your Post model yet—let's fix both of these.

Step 1: Register Your Custom Manager with the Post Model

First, update your models.py to include the PublishedManager in your Post class. Make sure to keep the default objects manager too (Django relies on it for some built-in features):

from django.db import models

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

class Post(models.Model):
    # Add your existing fields here (title, content, etc.)
    title = models.CharField(max_length=200)
    content = models.TextField()
    status = models.CharField(
        max_length=10,
        choices=[('draft', 'Draft'), ('published', 'Published')],
        default='draft'
    )
    # Default manager - keep this!
    objects = models.Manager()
    # Your custom published manager
    published = PublishedManager()

Step 2: Access the Manager Correctly (Via the Model Class, Not an Instance)

Now, to fetch published posts, call the manager directly on the Post class, not on a single Post object:

Correct Usage:

# Get all published posts
all_published = Post.published.all()

# Filter published posts by title
specific_published = Post.published.filter(title__icontains='django')

Wrong Usage (What's Causing Your Error):

# This will throw the "Manager isn't accessible via Post instances" error
my_post = Post.objects.get(id=1)
my_post.published.all()  # ❌ Don't do this!

Why This Works

Managers act as interfaces between your model and the database—they're designed to query sets of objects, not interact with individual instances. By registering the manager with the model class and calling it there, you're using Django's ORM as intended.

内容的提问来源于stack exchange,提问作者Goodness Ezeokafor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:37:18