0

I am working with a template in django trying to dispaly a specific number of random items from an array of related objects

for now i display all items in the array what changes can i make

 {% for pdt in object.pdt_set.all %} <div class="ps-product ps-product--simple"> <div class="ps-product__thumbnail"> <a href="{% url 'pdtdetail' pdt.id %}"><img src="{{ pdt.image.ur }}"alt=""></a> <div class="ps-product__badge">-16%</div> <ul class="ps-product__actions"> <li><a href="#" data-toggle="tooltip" data-placement="top" title="Read More"><i class="icon-bag2"></i></a></li> <li><a href="#" data-placement="top" title="Quick View" data-toggle="modal" data-target="#product-quickview"><i class="icon-eye"></i></a></li> <li><a href="#" data-toggle="tooltip" data-placement="top" title="Add to Whishlist"><i class="icon-heart"></i></a></li> <li><a href="#" data-toggle="tooltip" data-placement="top" title="Compare"><i class="icon-chart-bars"></i></a></li> </ul> </div> <div class="ps-product__container"> <div class="ps-product__content" data-mh="garden"><a class="ps-product__title" href="product-default.html">{{ pdt.name }}</a> <div class="ps-product__rating"> <select class="ps-rating" data-read-only="true"> <option value="1">1</option> <option value="1">2</option> <option value="1">3</option> <option value="1">4</option> <option value="2">5</option> </select><span>01</span> </div> <p class="ps-product__price sale">$ {{ pdt.price }} </p> </div> </div> </div> {% endfor %} 

1 Answer 1

1

Since you are using this queryset: {% for pdt in object.pdt_set.all %}

All you have to do is randomize it and limit how many results you select

{% for pdt in object.pdt_set.order_by('?').limit(5) %}

or

{% for pdt in object.pdt_set.order_by('?')[:5] %}

Replace 5 with however many records you want

See:

How to pull a random record using Django's ORM?

Django - limiting query results

Sign up to request clarification or add additional context in comments.

4 Comments

okay but according to those posts they say it is slow what's your take ? @AayushAgrawal
There's an old principle in programming - 'It's better to ask for forgiveness than to ask for permission' Try it. If it feels slow, don't use it. This will only be slow if pdt_set has millions or billions of records, and i have a feeling that is probably not the case here :)
been getting Could not parse the remainder: '('?')[:5]' errors any idea
@JordanRob That's caused by Jinja2 trying to prevent function execution. If you pass the entire variable object.pdt_set.order_by('?')[:5] from the View instead of evaluating in the template it should fix the problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.