Django pagination (get page no. corresponding to the object)

◇◆丶佛笑我妖孽 提交于 2019-12-05 13:31:22

It's not the best idea what you're doing. Try to imagine how many queries it'll be translated to -- in the worst case you'd need to retrieve all user's posts from database!

I assume that you have some predefined ordering in your Post model (the one that Paginator uses). Use that to obtain the number of user's posts that precede that specific post record. If you divide that number by the POSTS_PER_PAGE value you'll get your page number.

IMHO using PostManager in Post methods is ok. What's not ok is that you're passing request object to it while I think you should use user_id for that (and permission checking should be really part of a view logic).

EDIT: example

from django.db import models
from django.contrib.auth.models import User

POSTS_PER_PAGE = 10

class Post(models.Model):
    """
    >>> from datetime import datetime, timedelta
    >>> from django.db import connection
    >>> from django.conf import settings
    >>>
    >>> user = User.objects.create_user("test", "test@domain.com")
    >>> for i in xrange(100):
    ...     p = Post.objects.create(author=user,
    ...                             pub_date=datetime.now() - timedelta(hours=i))
    >>> post = Post.objects.all()[68]
    >>> settings.DEBUG = True    # monkey-patching settings - ugly
    >>> connection.queries = []  # cleaning previous queries
    >>> post.get_page()
    7
    >>> len(connection.queries)  # print number of queries of `get_page` call
    1
    """
    pub_date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User)
    class Meta:
        ordering = ["-pub_date"]

    def get_page(self):
        return self._default_manager.filter(author__id=self.author_id).filter(
            pub_date__gt=self.pub_date).count() / POSTS_PER_PAGE + 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!