网络编程
位置:首页>> 网络编程>> Python编程>> Django模板标签{% for %}循环,获取制定条数据实例

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

作者:qq_16853655  发布时间:2023-02-25 02:27:59 

标签:Django,标签,循环,for

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

返回查询结果的切片

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

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>

来源:https://blog.csdn.net/qq_16853655/article/details/103929970

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com