简体   繁体   中英

Get first object of query-set in Django templates

I understand that Django separates data and presentation such that Object.filter(id=value).all() isn't possible through templates.

What I'm struggling to understand is the best practice for achieving this same type of end result.

For example, in one of my apps I've data for products, which include some one-to-many relationships with images. That's to say, one product may have many images.

in my AppName/views.py file, I've got the following:

def index(request):

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

in my AppName/templates/AppName/index.html file, there's a section with the following:

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

What I'd like to be able to do, is include the equivalent of {{product.images.first().url}} in the mix.

What's the typical approach for this?

Several options, taken from here :

1-(an older approach):

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

2-Since Django 1.6ish

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM