Get first item of QuerySet in template

后端 未结 4 1195
野性不改
野性不改 2020-12-30 23:01

In my blog app I want to display a list of blog posts and the first image connected to this post. Now I do it this way:

{% for image in entry.image_set.all|s         


        
相关标签:
4条回答
  • 2020-12-30 23:40

    Since Django 1.6 you can do

    <img src="{{ entry.image_set.first.get_absolute_url }}">
    
    0 讨论(0)
  • 2020-12-30 23:45

    Not any shorter, but you could use first:

    {% with entry.image_set.all|first as image %}
      <img src="{{ image.get_absolute_url }}">
    {% endwith %}
    
    0 讨论(0)
  • 2020-12-30 23:45

    You also can do: entry.image_set.all.0 in your template.

    0 讨论(0)
  • 2020-12-30 23:51

    I was having the following queryset I just want to retrieve first element from it in jinja template.

    <QuerySet [<StudentDetails: StudentDetails object (1)>, <StudentDetails: StudentDetails object (2)>]>
    

    Solution

    {{ StudentDetails.first.name }}
    

    StudentDetails is my model

    0 讨论(0)
提交回复
热议问题