【问题标题】:Return the first image from the model using the tag '{{value | first}}'使用标签 '{{value | 返回模型中的第一张图像第一的}}'
【发布时间】:2019-07-01 16:53:24
【问题描述】:

我有一张照片列表,我希望始终首先将其添加为个人资料照片。我在 django 文档中找到了以下 '|first' 标记,但是在我的情况下添加它时遇到问题,每次我尝试以这种方式执行时,'{{ image_list|first.photo.url }}'我什么也没收到。

任何帮助将不胜感激。

我的models.py

class Image(models.Model):
    photo = models.ImageField()
    added_at = models.DateTimeField(auto_now_add=True)
    masseurs = models.ForeignKey(Masseurs, on_delete=models.CASCADE)

views.py

masseur = get_object_or_404(Masseurs, pk=masseurs_id)
image_list = Image.objects.filter(masseurs_id = masseurs_id)
return render(request, 'masseur/masseur_detail.html', {'image_list':image_list})

【问题讨论】:

标签: python django templates


【解决方案1】:

由于image_list 是一个查询集而不是一个列表,|first 将不起作用。但是,您可以使用:

{{ image_list.first.photo.url }}

参考见:Accessing Method Calls

大多数附加到对象的方法调用也可以在模板中使用。这意味着模板可以访问的不仅仅是类属性(如字段名称)和从视图传入的变量。

【讨论】:

  • 是否也可以在问题中的这种情况下使用“切片”的等价物?如果是这样,它会是什么样子(例如来自文档示例 {{ some_list|slice:":2" }})?
  • 您可以在视图中对查询集进行切片,是的。 {% with image_list|slice:'0' as image %} {{ image.photo.url }} {% endwith %} 我敢打赌,这条路线会比使用模型方法慢得多。也可以通过索引访问{{ image_list.0.photo.url }}
  • 所以你建议从模型视图中获取照片?
【解决方案2】:

为什么不在视图中做呢?

image = Image.objects.filter(masseurs_id=masseurs_id).first()

但如果需要在模板中做:

{{ image_list.first.photo.url }}

这是因为image_list是一个查询集,所以可以用.first()语法获取查询集的第一项

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2013-05-12
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多