Django博客下一个/上一个条目

时间:2017-05-30 10:12:27

标签: python django

我的博客有5种帖子,3种有详细页面,2种没有详细页面,我必须按帖子ID搜索上一篇和下一篇文章,如果以前没有详细页面,继续,这里是我的代码:

class Post_detail_View(View):
def get(self,request,post_id):
    try:
        post = Post.objects.select_related('standardpost', 'quotepost', 'linkpost', 'audiopost', 'videopost').get(pk=post_id)
        previous = self.get_previous(post_id)
        next_post = self.get_next(post_id)

        if post.type == 'standard':
            content = markdown.markdown(post.standardpost.content, extensions=['markdown.extensions.extra',
                                                                                'markdown.extensions.codehilite',
                                                                                'markdown.extensions.toc', ])
            return render_to_response('post-detail.html', locals())
        elif post.type == 'audio':
            content = markdown.markdown(post.audiopost.content, extensions=['markdown.extensions.extra',
                                                                            'markdown.extensions.codehilite',
                                                                            'markdown.extensions.toc', ])
            return render_to_response('post-detail.html', locals())

        elif post.type == 'video':
            content = markdown.markdown(post.videopost.content, extensions=['markdown.extensions.extra',
                                                                            'markdown.extensions.codehilite',
                                                                            'markdown.extensions.toc', ])
            return render_to_response('post-detail.html', locals())
    except:
        raise Http404

def get_previous(self,post_id):

    post_id = int(post_id)
    if post_id > 1:
        try:
            previous = Post.objects.select_related('standardpost', 'quotepost', 'linkpost', 'audiopost','videopost').get(pk=str(post_id - 1))
            if previous.type == 'quote' or previous.type == 'link':
                if post_id - 1 > 1:
                    self.get_previous(str(post_id - 1))
                else:
                    return 0
            else:
                return previous
        except:
            return 0
    else:
        return 0

def get_next(self,post_id):
    post_id = int(post_id)
    try:
        next_post = Post.objects.select_related('standardpost', 'quotepost', 'linkpost', 'audiopost','videopost').get(pk=str(post_id + 1))
        if next_post.type == 'quote' or next_post.type == 'link':
            self.get_next(str(post_id + 1))
        else:
            return next_post
    except:
        return 0

我调试此previous = self.get_previous(post_id) next_post = self.get_next(post_id)

在一次或多次递归之后,在返回之前,它们都有返回的对象,但是在返回后它们将变为None,如果直接返回没有递归,它就没问题了。

返回前

before return

退货后

after return

0 个答案:

没有答案