django 个人博客系统开发 - 代码重构 聚合查询

来源:互联网 发布:html编程软件 编辑:程序博客网 时间:2024/04/25 14:02

*视图函数重构

def global_setting(request):    SITE_NAME = settings.SITE_NAME    WEIBO_SINA = settings.WEIBO_SINA    categories = Cateory.objects.all()    archives = Article.objects.distinct_date()    return locals()

定义通用函数

def paging_articles(request, articles):    paginator = Paginator(articles, 2)    try:        page = int(request.GET.get('page', 1))        articles = paginator.page(page)    except PageNotAnInteger:        articles = paginator.page(1)    except EmptyPage:        articles = paginator.page(paginator.num_pages)    return articles

def index(request):    try:        articles = Article.objects.all()        articles = paging_articles(request, articles)    except Exception as e:        print(e)        logger.error(e)    return render(request, 'index.html', locals())

*重构urls

urlpatterns = [    url(r'^admin/', include(admin.site.urls)),    url(r'', include('blog.urls')),#    url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),]#...

blog.urls

from django.conf.urls import  urlfrom .views import *urlpatterns = [    url(r'^$', index , name='index'),    url(r'^archive/$', archive, name = 'archive'),]


*模板的重构

提取分页的公用部分为 pagination.html

修改以支持归档视图的分页

{% load staticfiles %}<div>    <ui>        {% if articles.has_previous %}            <li><a href="?page={{ articles.previous_page_number }}{% if request.GET.year %}&year={{ request.GET.year }}{% endif %}{% if request.GET.month %}&month={{ request.GET.month }}{% endif %}">«上一页</a></li>        {% else %}            <li>«上一页</li>        {% endif %}        <li>{{ articles.number }}/{{ articles.paginator.num_pages }}</li>        {% if articles.has_next %}            <li><a href="?page={{ articles.next_page_number }}{% if request.GET.year %}&year={{ request.GET.year }}{% endif %}{% if request.GET.month %}&month={{ request.GET.month }}{% endif %}">下一页»</a></li>        {% else %}            <li>下一页»</li>        {% endif %}    </ui></div>

*聚合查询 按评论排行的实现

https://docs.djangoproject.com/en/1.9/topics/db/aggregation/

from django.db.models import Count...def global_setting(request):    SITE_NAME = settings.SITE_NAME    WEIBO_SINA = settings.WEIBO_SINA    categories = Cateory.objects.all()    archives = Article.objects.distinct_date()    hotArticles = Article.objects.annotate(num_comments=Count('comment')).order_by('-num_comments')[:5]#聚合查询    return locals()






0 0