1

When I want to show a queryset passed to a template in Django, and there is only one record, is it necessary to loop?

I have something like:

{% for x in blobs%}
    {{ x.id }}
{% endfor %}

Which works fine. But only one record is in blobs, as it was filtered to a specific id by the view.

Would it not be better than to just access {{blobs.id}} directly? If so, what is the correct way to do that?

Jake Rankin
  • 714
  • 6
  • 22
  • Hey, it'd be better if you also add the queryset you're using. – prakasht Jun 27 '20 at 14:10
  • @prakasht I didn't think that was relevant. It has an id field which displays when looping over it, I just want to access it outside of the loop. – Jake Rankin Jun 27 '20 at 14:12
  • 1
    Can you use objects.get() instead of objects.filter(), i.e., only send the object to template? You can also try index based lookup, see https://stackoverflow.com/questions/4651172/reference-list-item-by-index-within-django-template – prakasht Jun 27 '20 at 14:31
  • 1
    if you sure that there would be only one result, you can add `blob.first()` to your template context instead of adding blob/ and then you can use `blob.id` in template. but if you sure that you always have only 1 result in your queryset, that don't use `Model.objects.filter(id=...)`, use `Model.objects.get(pk=...)` – Andrey Maslov Jun 27 '20 at 14:55
  • @AndreyMaslov thank you for explaining, that is good advice, I will implement now! – Jake Rankin Jun 27 '20 at 14:59

1 Answers1

2

Assuming you blobs is a list, you cant access like that. your blobs is list with one element. something like [blob,] this. In a python script you can access that like blobs[0].id and to achieve that in template you can do {{blobs.0.id}}

mursalin
  • 1,151
  • 1
  • 7
  • 18