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='http://www.aoyou183.cn/bcjs/{{ picture.get_absolute_url }}' rel='external nofollow' rel='external nofollow' rel='external nofollow' ><img src='http://www.aoyou183.cn/bcjs/{{ picture.image.url }}' alt='ins-picture'/></a> <div class='info'><h4><a href='http://www.aoyou183.cn/bcjs/{{ picture.get_absolute_url }}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >{{ picture.post_updated }}</a></h4><h3><a href='http://www.aoyou183.cn/bcjs/{{ 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>
以上這篇Django模板標簽{% for %}循環,獲取制定條數據實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。