欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Django模板标签{% for %}循环,获取制定条数据实例

时间:2021-06-24 08:21:53|栏目:Python代码|点击:

有时候,为了获取查询结果的部分数据,需要对变量进行一些处理,在网上查了一圈,只发现了这两个方法:

返回查询结果的切片

在返回给前端的结果中,通过切片来取得想要的数据:

pictures = Post.objects.filter(status='published')[:8]

如[:8],但这种操作比较片面,会将返回结果限制住,有时候不利于其他的操作使用

2.使用{% if %}标签和forloop.counter变量来获取:

 <h3>最新博文</h3>
     {% for picture in pictures %}
      {% if forloop.counter > 2 %}
        {% if forloop.counter < 4 %}
      <div class="pop-post"><a href="{{ picture.get_absolute_url }}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><img src="{{ picture.image.url }}" width="100" height="80" alt="ins-picture"/></a>
       <div class="info">
        <h4><a href="{{ picture.get_absolute_url }}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ picture.post_updated }}</a></h4>
        <h3><a href="{{ picture.get_absolute_url }}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ picture.title }}</a></h3>
       </div>
      </div>
        {% endif %}
      {% endif %}
     {% empty %}
     <p>暂无文章!</p>
     {% endfor %}

通过对forloop.counter的判断,来确定需要用在前端上的数据,forloop.counter用来统计for循环的次数,从1开始技术,也有forloop.counter0,是从0开始计数

补充知识:python3--django for 循环中,获取序号

功能需求:在前端页面中,for循环id会构不成连续的顺序号,所以要找到一种伪列的方式来根据数据量定义序号

因此就用到了在前端页面中的一个字段 forloop.counter,完美解决

<tbody>
   {% for inrow in insocket_list %}
   <tr>
      <!-- 这是序列号(相当于伪列)-->
      <td>{{ forloop.counter }}</td>
      <td>{{ inrow.inequip }}</td>
      <td>{{ inrow.inmodel }}</td>
      <td>{{ inrow.innumber }}</td>
      <td>{{ inrow.stocknumber }}</td>
      <td>{{ inrow.inusername }}</td>
      <td>{{ inrow.inestablishtime }}</td>
      <td>{{ inrow.remarks }}</td>
   </tr>
   {% endfor %}
</tbody>

上一篇:python找出完数的方法

栏    目:Python代码

下一篇:使用豆瓣源来安装python中的第三方库方法

本文标题:Django模板标签{% for %}循环,获取制定条数据实例

本文地址:http://www.codeinn.net/misctech/147504.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有