Django模板標(biāo)簽{% for %}循環(huán),獲取制定條數(shù)據(jù)實(shí)例
有時候,為了獲取查詢結(jié)果的部分?jǐn)?shù)據(jù),需要對變量進(jìn)行一些處理,在網(wǎng)上查了一圈,只發(fā)現(xiàn)了這兩個方法:
返回查詢結(jié)果的切片
在返回給前端的結(jié)果中,通過切片來取得想要的數(shù)據(jù):
pictures = Post.objects.filter(status=’published’)[:8]
如[:8],但這種操作比較片面,會將返回結(jié)果限制住,有時候不利于其他的操作使用
2.使用{% if %}標(biāo)簽和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的判斷,來確定需要用在前端上的數(shù)據(jù),forloop.counter用來統(tǒng)計for循環(huán)的次數(shù),從1開始技術(shù),也有forloop.counter0,是從0開始計數(shù)
補(bǔ)充知識:python3--django for 循環(huán)中,獲取序號
功能需求:在前端頁面中,for循環(huán)id會構(gòu)不成連續(xù)的順序號,所以要找到一種偽列的方式來根據(jù)數(shù)據(jù)量定義序號
因此就用到了在前端頁面中的一個字段 forloop.counter,完美解決
<tbody> {% for inrow in insocket_list %} <tr> <!-- 這是序列號(相當(dāng)于偽列)--> <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模板標(biāo)簽{% for %}循環(huán),獲取制定條數(shù)據(jù)實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
