0

The views.py file has the following code:

def index(request):
    post = Product.objects.all()

    context = {
        "post":post
    }
    return render(request, "index.html", context)

And my template has the following code:

<div class="features_items"><!--products --- features_items-->
                        <h2 class="title text-center">Your Product Feed</h2>
                        {% for p in post|slice:":50" %}

                        <div class="col-sm-4", id="items">
                            <div class="product-image-wrapper">
                                <div class="single-products">
                                        <div class="productinfo text-center  shadow p-3 mb-5 bg-white rounded" style="
                                        border-style: solid;
                                        border-width:0.1px;
                                         color: #E0E0E0;">
                                            <a href="{{ p.product_url }}"><img src="{{ p.product_image }}" alt="" /></a>

                                            <h6 style="color: #666663"> {{ p.product_price }}  &#2547; </h6>
                                        <a href="{{ p.product_url }}">  <p>{{ p.product_name|truncatewords:5 }}</p></a>

                                      <a href="#" style="color: #06c1bc;"><span class="glyphicon glyphicon-heart-empty"></span> Like</a>
                                             <a href="{{ p.product_url }}" style="color: #06c1bc; padding-left: 10px"><span class="glyphicon glyphicon-eye-open"></span> Detail</a>
                                        </div>

                                </div>
                                <div class="choose">
                                    <ul class="nav nav-pills nav-justified">
{#                                      <li><a href="#" class="btn btn-info btn-lg"><span class="glyphicon glyphicon-heart"></span> Like</a></li>#}
{#                                      <li><a href="#" class="btn btn-info btn-lg"><span class="glyphicon glyphicon-thumbs-down"></span> Unlike</a></li>#}
                                    </ul>
                                </div>
                            </div>
                        </div>


                         {% endfor %}

                    </div>

I want to show products coming from database are random (shuffled), not ordered by their ID. What change should I bring to my code?

sksoumik
  • 845
  • 1
  • 9
  • 23

1 Answers1

1

Simply do this:

    post = Product.objects.all().order_by("?")
sebb
  • 1,956
  • 1
  • 16
  • 28
  • 1
    Thanks. Worked. @sebb – sksoumik Mar 09 '19 at 18:10
  • 1
    `order_by("?")` might not be a good idea in production. An alternative is explained [here](https://stackoverflow.com/questions/962619/how-to-pull-a-random-record-using-djangos-orm) – Thom Mar 09 '19 at 18:30