码迷,mamicode.com
首页 > 其他好文 > 详细

分页器 Paginator使用、自定义manager管理器

时间:2017-10-15 19:48:33      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:ima   ber   作用   except   包含   cts   core   -o   cti   

分页使用以及异常处理

#_*_* coding: utf-8 _*_*
from django.shortcuts import render
import logging
from django.conf import settings
from models import *
from django.core.paginator import  Paginator,InvalidPage,EmptyPage,PageNotAnInteger
# Create your views here.

logger = logging.getLogger(blog.views)


def global_setting(request):
    return {
        SITE_NAME : settings.SITE_NAME,
    SITE_DESC : settings.SITE_DESC
    }


def index(request):
    try:
        #分类信息的获取(导航)

        #广告数据
         #最新文章获取
        article_list = Article.objects.all()
        paginator = Paginator(article_list,10) #每一页显示10条
        try:
            page = int(request.GET.get(page,1)) #获取当前页,没有找到数据 就返回第一页
            article_list = paginator.page(page)
        except (EmptyPage,InvalidPage,PageNotAnInteger):
            article_list = paginator.page(1) #出现异常就跳到第一页
    except Exception as e:
        logger.error(e)
    return render(request,index.html,locals()) #local 当前所有的作用域

index下的分页

<div id="pagination">
    <ul id="pagination-flickr">
    {% if article_list.has_previous %}
    <li class="previous"><a href="?page={{ article_list.previous_page_number }}">&laquo;上一页</a></li>
    {% else %}
    <li class="previous-off">&laquo;上一页</li>
    {% endif %}
     <li class="active">{{ article_list.number }}/{{ article_list.paginator.num_pages }}</li>
    {% if article_list.has_next %}
       <li class="next"><a href="?page={{ article_list.next_page_number }}">下一页 &raquo;</a></li>
    {% else %}
      <li class="next-off">下一页 &raquo;</li>
    {% endif %}
   </ul>
</div>

这种方式不推荐  直接见第二种

1、使用filter()进行查询
2、values(),distinct()的使用
3、django中直接使用sql的两种方式
SELECT DISTINCT DATE_FORMAT(date_publish, ‘%Y-%m‘) as col_date FROM blog_article ORDER BY date_publish
3.1、raw (异常:Raw query must include the primary key,返回结果必须包含主键)
3.2、excute

 # Article.objects.values(‘date_publish‘).distinct()  #去除重复,文章发布时间精确到秒 所有用着合格方法有点行不通
            # cursor = connection.cursor()
            # cursor.execute("SELECT DISTINCT DATE_FORMAT(date_publish, ‘%%Y-%%m‘) as col_date FROM blog_article ORDER BY date_publish")
            # row = cursor.fetchall()
            # print  row

 

分页器 Paginator使用、自定义manager管理器

标签:ima   ber   作用   except   包含   cts   core   -o   cti   

原文地址:http://www.cnblogs.com/Mjonj/p/7672915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!