【问题标题】:Django ListView how loop in one field in the template?Django ListView 如何在模板的一个字段中循环?
【发布时间】:2021-07-04 03:49:24
【问题描述】:

我有 django ListView 我知道我可以像这样循环它

{% for i in object_list %}
{% i.id %}
{% endfor %}

我只想在一个字段中循环

{% for i in object_list.id %}
{% i %}
{% endfor %}

更新:

我的模特:

class Weather(models.Model):
temperature = models.FloatField(
    validators=[MaxValueValidator(28), MinValueValidator(19)]
)
humidity = models.FloatField(
    validators=[MaxValueValidator(65), MinValueValidator(35)]
)
time_recorded = models.DateTimeField(auto_now_add=True, blank=True)

列表视图:

class WeatherListView(ListView):

template_name = "frontend/weather_list.html"
model = Weather

我想在 html 模板中的不同位置循环这些字段中的每一个,所以我不想每次都在整个列表中循环,例如,如果我只想循环温度: 我想这样做:

{% for i in object_list.temperature %}
{% i %}
{% endfor %}

代替:

{% for i in object_list %}
{% i.temperature %}
{% endfor %}

【问题讨论】:

  • 请显示您尝试循环的模型类和 ListView 的视图代码
  • @LinhNguyen 我更新了我的帖子
  • {% for i in object_list %} {{ i.temperature }} {% endfor %} 工作正常。为什么不想这样写呢?
  • @jaap3 我想优化我的代码,如果我只想要 1 个字段,为什么要循环整个上下文,尤其是我在模板中多次使用它,如果我的上下文有多个字段而不仅仅是 3 .

标签: django django-templates django-template-filters


【解决方案1】:

好的,我认为模板中的object_list 代表什么存在误解。您不是在“整个上下文”上循环。 object_list 是上下文中的变量,表示特定视图的QuerySet

对于WeatherListView,它是Weather.objects.all()。因此,当您编写 {% for i in object_list %} 时,您将遍历数据库中的所有 Weather 实例。

我不确定您要优化什么。也许是数据库查询的数量?在那种情况下,我可以告诉你,Django 中的 QuerySets 是惰性求值的,但是一旦求值,结果就会被缓存。因此,如果您在下次循环时循环一次 object_list,它将不会导致新的数据库查询。

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多