Django 项目试炼blog(5) -- 个人站点的搭建

urls

    # 个人站点url   一个试图实现http://127.0.0.1:8000/xjj/cate/xjj的mysql/  与 http://127.0.0.1:8000/xjj/ 的跳转
    re_path(r'^(?P<username>\w+)/$',views.per_site),
    re_path(r'^(?P<username>\w+)/(?P<style>tag|cate|date)/(?P<info>.*)/$',views.per_site),

  有名分组?P<>,将参数转变为实参,per_site(request,username), per_site(request,username,“tag|cate|date”,info)。

  re_path中一个()即为一个参数


views(功能实现面板信息跳转对应的文章,与默认页面全部文章显示)

from django.db.models import Count
def per_site(request,username,**kwargs):
    res = UserInfo.objects.filter(username=username).first()
    if res:
        # http: // 127.0.0.1: 8000 / zzw / cate / python /
        if kwargs:
            style = kwargs['style']
            info = kwargs['info']
            if style == 'cate':
                art_list = Article.objects.filter(user_id=res.pk).filter(category__title=info)
            elif style == 'tag':
                art_list = Article.objects.filter(user_id=res.pk).filter(tag__title=info)
            else:
                # 调整时区 settings USE_TZ = False
                year,month = info.split('-')
                print(year,month)
                art_list = Article.objects.filter(user_id=res.pk).filter(create_time__year=year,create_time__month=month)
                print(art_list)
        else:
            art_list = Article.objects.filter(user_id=res.pk)  # 显示站点内的所有文章

        # 显示站点内每个分类对应的文章数
        cate_list = Category.objects.filter(blog_id=res.pk).annotate(c=Count('article__category_id')).values('title','c')

        # 显示站点内每个分类对应的文章数
        tag_list = Tag.objects.filter(blog_id=res.pk).annotate(c=Count('article2tag__tag_id')).values('title','c')

        #显示每月的博客数
        date_list = Article.objects.filter(user_id=res.pk).extra({'date':"date_format(create_time,'%%Y-%%m')"}).values('date').annotate(c=Count('nid')).values('date','c')

        return render(request,'per_site.html',locals())
    else:
        return render(request,'no_user.html')

为了避免再开一条路由,巧妙利用**kwargs(如果没有参数,就正常执行,有参数即按字典传入函数,{'style':‘cate’,'info':xxx})

ORM中extra自建sql语句的用法


前端:

<div class="col-md-9">
    <h4>文章摘要</h4>
    {% for art in art_list %}
         <div>
            <a href="" ><span>{{ art.title }}</span></a>
            <p >{{ art.desc }}</p>
            <p class="pull-right " ><span>{{ art.create_time|date:'Y-m-d H:m' }}</span>  #过滤器的使用
                <span>{{ art.user.username }}</span></p>
        </div>
        <hr style="clear: both">
    {% endfor %}

  


重点:

1、ORM中的跨表查询

正向查询:关联属性(放在‘多’一方)在A表中  A-->B           正向按字段(models—class中生成的关联字段)

反向查询:B-->A                                            反向按表名小写

2、在过滤时间时,注意setting中的市区设置 USE-TZ = Flase

3、路由re_path正则匹配

猜你喜欢

转载自www.cnblogs.com/zhuzhiwei-2019/p/10754131.html