如何反转 Django 模板中的 for 循环,然后对结果进行切片 [英] How to reverse a for loop in a Django template and then slice the result

查看:30
本文介绍了如何反转 Django 模板中的 for 循环,然后对结果进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Django 模板中,我遍历一组照片,并一张一张地显示它们.具体来说,现在我只有一组照片,包含 6 个对象.我像这样显示这 6 个对象:

In a Django template, I'm iterating over a set of photos, and displaying them one by one. Specifically, right now I just have one photo set, containing 6 objects. I display these 6 objects like so:

{% for pic in picstream.photo_set.all reversed %}
    <img src="{{ pic.image_file.url }}"></img>
{% endfor %}

在语句中添加 reversed 给了我所需顺序的 6 个对象(即最新的 id 首先).

Adding reversed to the statement gives me the 6 objects in the desired ordering (i.e. the latest ids first).

接下来,我想显示 photo_set 中不超过 4 个的对象.我将 |slice:":4" 添加到 picstream.photo_set.all 以实现此目的.问题是,它从我想要的排序中切断了前两个对象

Next, I want to display not more than 4 objects from the photo_set. I added |slice:":4" to picstream.photo_set.all to achieve this. Problem is, it's cutting off the first two objects from my desired oredering.

似乎应该有一种方法可以将列表反转,然后稍后切片?需要一种简单的方法来做到这一点,而不会影响性能.

It seems there ought to have been a way to reverse the list first, and slice later? Need a simple way to do this, without performance compromises.

推荐答案

代替使用 reversed 参数作为 for 模板标签,您可以使用 查询集本身的反向方法:

Instead of using the reversed argument for the for template tag, you can use the reverse method of the queryset itself:

{% for pic in picstream.photo_set.all.reverse|slice:":4" %}
    <img src="{{ pic.image_file.url }}"></img>
{% endfor %}

如果您正在评估代码中其他地方的原始(非反向)查询集,那么这将导致第二个查询访问数据库.如果是这种情况,那么最好将逻辑移到视图代码本身或模板标记中.

If you are evaluating the original (non-reversed) queryset somewhere else in your code then this will result in a second query hitting the database. If this is the case then you are better off moving the logic into your view code itself or into a template tag.

这篇关于如何反转 Django 模板中的 for 循环,然后对结果进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆