I'd like to get a QuerySet of a Model in Manager's __init__
method to setup Pagination for the QuerySet results. The reason why I want to setup Pagination in __init__
method is because I have lots of simple methods in the Manager like getPage
and getNumberOfPages
etc. to simplify abstraction and I don't want to duplicate the code to setup Paginator
across all these methods.
For example, let's say that there is an Article
model, which has a custom ArticleManager
and it looks somewhat like this:
class ArticleManager(models.Manager):
def __init__(self):
super(ArticleManager, self).__init__()
allObjects = super(ArticleManager, self).get_queryset()
self.articlePaginator = Paginator(allObjects, 10)
class Article(models.Model):
# blah blah
# Model fields everywhere
objects = ArticleManager()
Fourth line of this code that is super(ArticleManager, self).get_queryset()
returns an AttributeError
exception:
AttributeError: 'NoneType' object has no attribute '_meta'
I guess I should have done something more to properly initialize the Manager, but I'm not sure what it is. I've not found anything alike I want in Django docs or in other StackOverflow questions. Also I guess there might be something wrong in my approach, so if that's the case I'd be grateful if somebody would point that out.
You're calling the parent's get_query()
method. You're not overriding it so there's no point, just call it on self
. Better yet, make this operation lazy. Properties are an option:
class ArticleManager(models.Manager):
@property
def article_paginator(self):
return Paginator(self.get_queryset(), 10)
Then you can access it via Article.objects.article_paginator
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.