zoukankan      html  css  js  c++  java
  • 125-django的标签,条件过滤

    使用model.objects.filter()进行过滤时,()内左侧只能是model的某个属性,貌似不能是表达式,尝试了很久都不行!

    这里,以tag为例还进行筛选:

    首先看模板的写法:

    {%block side %}
    <div class="right">
        <div id="index">
            <h3><a href="{% url 'notebook:my_notes' 1 %}">日期索引(返回全部)</a></h3>
            {% for date in date_index %}
            <li><a href="{% url 'notebook:date_notes' date %}">{{date}}</a></li>
            {% endfor %}
            </ul>
        </div>
        <div id="tag">
            <h3><a href="{% url 'notebook:my_notes' 1 %}">标签索引(返回全部)</a></h3>
            {% for tag in tag_index %}
                <span><a href="{% url 'notebook:tag_notes' tag %}">{{tag}}</a></span>
            {% endfor %}
        </div>
    </div>
    {% endblock side %}
    

      

    如果列举了一个tag,在点击链接后,会向url直接传递这个tag。

    接下来看views函数会如何处理:

    def tag_notes(request, tag):
        date_and_tag()
        all_tag_notes = MyNote.objects.filter(personal_tags__name__in=[tag])
        context = {'all_tag_notes': all_tag_notes, 'date_index': list(set(date_list)),
                   'tag_index': list(set(tag_list))}
        return render(request, 'tag_notes.html', context)
    

      

    首先从url里获得传递来的值;

    如果要使用包含筛选,需要使用对应字段名+__name__in,注意:这里是双下划线!其后面对应一个列表,列表里当前只有一个值,就是url里传来的值。

    通过这种方式,我们就能获得所有包含指定标签的文章了。

  • 相关阅读:
    课堂练习——找水王续
    电梯调度设计
    团队冲刺阶段一第五次站立会议
    团队冲刺阶段一第四次站立会议
    团队冲刺阶段一第三次站立会议
    团队冲刺阶段一第二次站立会议
    团队冲刺阶段一第一次站立会议
    《你的灯亮着吗》读书笔记三
    《你的灯亮着吗》读书笔记二
    《你的灯亮着吗》读书笔记一
  • 原文地址:https://www.cnblogs.com/lzhshn/p/13558586.html
Copyright © 2011-2022 走看看