Django模板標簽{% for %}循環(huán),獲取制定條數(shù)據(jù)實例
有時候,為了獲取查詢結果的部分數(shù)據(jù),需要對變量進行一些處理,在網(wǎng)上查了一圈,只發(fā)現(xiàn)了這兩個方法:
返回查詢結果的切片
在返回給前端的結果中,通過切片來取得想要的數(shù)據(jù):
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的判斷,來確定需要用在前端上的數(shù)據(jù),forloop.counter用來統(tǒng)計for循環(huán)的次數(shù),從1開始技術,也有forloop.counter0,是從0開始計數(shù)
補充知識:python3--django for 循環(huán)中,獲取序號
功能需求:在前端頁面中,for循環(huán)id會構不成連續(xù)的順序號,所以要找到一種偽列的方式來根據(jù)數(shù)據(jù)量定義序號
因此就用到了在前端頁面中的一個字段 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 %}循環(huán),獲取制定條數(shù)據(jù)實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解用Pytest+Allure生成漂亮的HTML圖形化測試報告
這篇文章主要介紹了詳解用Pytest+Allure生成漂亮的HTML圖形化測試報告,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
python執(zhí)行數(shù)據(jù)庫的查詢操作實例講解
在本篇文章里小編給大家整理了一篇關于python執(zhí)行數(shù)據(jù)庫的查詢操作實例講解內(nèi)容,有需要的朋友們可以參考學習下。2021-10-10
解決List.append()?在?Python?中不起作用的問題
在?Python?中,我們通常使用?List.append()?方法向列表末尾添加元素,然而,在某些情況下,你可能會遇到?List.append()?方法不起作用的問題,本文將詳細討論這個問題并提供解決方法,需要的朋友可以參考下2023-06-06

