Django 1.10报错‘Manager isn't accessible via Post instances’求助
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

