【问题标题】:Get first object of query-set in Django templates在 Django 模板中获取查询集的第一个对象
【发布时间】:2018-06-06 00:51:21
【问题描述】:

我了解 Django 将数据和表示分离,因此 Object.filter(id=value).all() 无法通过模板实现。

我很难理解的是实现相同类型最终结果的最佳实践。

例如,在我的一个应用中,我有产品数据,其中包括一些与图像的一对多关系。也就是说,一个产品可能有很多图片。

在我的AppName/views.py 文件中,我有以下内容:

def index(request):

    response = render_to_response('AppName/index.html', context={
        'products': Product.objects.all(),
    })
    return response

在我的AppName/templates/AppName/index.html 文件中,有一个部分包含以下内容:

{% for product in products %}
    <li>{{ product.name }}: ${{ product.price }}</li>
{% endfor %}

我想做的就是在组合中包含 {{product.images.first().url}} 的等价物。

对此的典型方法是什么?

【问题讨论】:

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


【解决方案1】:

几个选项,taken from here:

1-(一种较旧的方法):

{% with entry.image_set.all|first as image %}
  <img src="{{ image.get_absolute_url }}">
{% endwith %}

2-从 Django 1.6 开始

<img src="{{ entry.image_set.first.get_absolute_url }}">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 2011-07-04
    • 2012-12-28
    • 2023-03-07
    • 2021-09-20
    • 1970-01-01
    • 2021-02-25
    相关资源
    最近更新 更多