Search code examples
pythondjangodjango-managers

When I define a custom manager .. Error:Manager isn't accessible via Post instances


I defined a custom manager inheriting models. Manager put in in my model 'Post'. The error says that you cant call manager through a instance but i have not called it through a instance it works fine when i remove the custom manager.

models.py:

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

class Post(models.Model):
    STATUS_CHOICES = [
        ('draft','Draft'), ('published','Published'),
        ]
    id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
    published = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='Published')
    author = models.ForeignKey(CustomUser,on_delete=models.CASCADE)
    body = models.TextField()
    objects = models.Manager()
    published = PublishedManager()
    

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("detail", kwargs={"slug":self.slug,"id": self.id})

views.py:

class PostListView(ListView):
    model = Post
    template_name = 'blog/index.html'
    context_object_name='posts'

Error image


Solution

  • I think you cannot have a manager named the same as the field of a Model. Try to rename it to something like published_objects.

    The error occurs when you try to access post.published (a field) but Django thinks you want to access a manager, hence the error.