zoukankan      html  css  js  c++  java
  • 上下篇博客,按月归档

    1.对比当前博客,得到上一篇或下一篇博客

    def blog_detail(request, blog_pk):
    context = {}
    blog = get_object_or_404(Blog, pk=blog_pk)
    context['previous_blog'] = Blog.objects.filter(created_time__gt=blog.created_time).last()
    context['next_blog'] = Blog.objects.filter(created_time__lt=blog.created_time).first()
    context['blog'] =blog
    return render(request, 'blog/blog_detail.html', context)
    通过filter筛选条件查找出符合的博客,查找出的结果是QuerySet和列表看起来一样,last()取到最后一篇。大于:__gt,大于等于:__gte,小于:__lt,小于等于:__lte,
    包含:__contains(加i忽略大小写),开头是:__startswith,结尾是:__endswith,其中之一:__in,范围:__range。exclude排除条件,与filter相反。
    条件中的双下划线:字段查询类型、外键拓展、日期拓展、支持链式查询

    在前端页面展示:
    <div class="blog-more">
    <p>上一篇:
    {% if previous_blog %}
    <a href="{% url 'blog_detail' previous_blog.pk %}">{{ previous_blog.title }}</a>
    {% else %}
    没有了
    {% endif %}
    </p>
    <p>下一篇:
    {% if next_blog %}
    <a href="{% url 'blog_detail' next_blog.pk %}">{{ next_blog.title }}</a>
    {% else %}
    没有了
    {% endif %}
    </p>
    </div>

    2.按月归档Django
    dates(field,kind,order='ASC')
    field字段,kind类型,order排序
    返回一个QuerySet
    context['blog_dates'] = Blog.objects.dates('created_time', 'month', order='DESC')
    根据博客创建时间的不同年份不同月份,返回日期列表 如果在10月的不同日期都创建了,只会返回10.1日。
    <QuerySet [datetime.date(2020, 10, 1)]>
    def blogs_with_date(request,year, month):
    blogs_all_list = Blog.objects.filter(created_time__year=year,created_time__month=month)
    根据前端传过来的年月筛选出所有博客
    context['blogs_with_date'] = '%s年%s月' % (year,month)
    给前端传入年月
    urlpatterns = [
    path('',views.blog_list,name='blog_list'),
    path('<int:blog_pk>/', views.blog_detail, name='blog_detail'),
    path('type/<int:blog_type_pk>/', views.blogs_with_type, name='blogs_with_type'),
    path('date/<int:year>/<int:month>', views.blogs_with_date, name='blogs_with_date'),
    ]
    url设置路由的格式。


  • 相关阅读:
    信号量Semaphore
    回环屏障CyclicBarrier
    线程同步器CountDownLatch
    vue 类似微信通讯录格式实现网易云音乐的歌手字母查询
    vue使用element的多个表格使用v-if切换,使用 :key="Math.random()" 后,表格排序出现问题
    vue使用pinyin的npm包将文字转为大写首字母字母
    vue中使用better-scroll滚动无效
    vue 移动端 图片懒加载 lazy
    表格配合keepalive缓存
    在保存数据之后,不知道什么时候清空数据,不如试试beforeRouteEnter
  • 原文地址:https://www.cnblogs.com/lag1/p/13820808.html
Copyright © 2011-2022 走看看