1

I have a view that contains code to retrieve all review objects for a movie:

review = Review.objects.filter(movie= movie)

How can I loop through these values in the html so that I only get the first 3 review objects? Indexing like review[0] doesn't seem to work.

I saw in another post that you can loop through all of the objects in the html like this (but this is not what I am looking for):

{% for obj in review %} 
  <p> {% obj.review_text %} </p>
{% endfor %}

3 Answers 3

2

Why not just get the first 3 items only in your view and only return those into the context? That seems like it would be the simplest solution.

first_3_reviews = Review.objects.filter(movie= movie)[:3]

Alternatively, you could use the forloop counter (see: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for) to only display the first 3 elements:

{% for obj in review %} 
  {% if forloop.counter < 3 %} 
    <p> {% obj.review_text %} </p>
  {% endif %} 
{% endfor %}
Sign up to request clarification or add additional context in comments.

3 Comments

This answer is great and works. I agree that this should be done in the view. Thank you for these solutions.
If you don't mind me asking, how would you go about filtering the last 3 items instead of the first 3. I tried review = Review.objects.filter(movie= movie).reverse()[:3]. This didn't work
To get the last three items you have to filter the queryset first. The hyphen before '-id' is important and orders the queryset in ascending order. This is the code I used: review = Review.objects.filter(movie= movie).order_by('-id')[:3]
1

try using

{% for obj in review %}
<p> {{% obj.review_text %}} </p>
{% endfor %}    

It will give you option to use your object easily

1 Comment

This doesn't address my question. I included that code in my original post
1
{% for obj in review[-3:] %}

this retrieves the last 3 items in review

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.