如何在Django中从整个数据库中随机整理帖子?

时间:2019-03-09 17:57:36

标签: django

views.py文件具有以下代码:

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

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

我的模板具有以下代码:

<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>

我想显示来自数据库的产品是随机的(随机),而不是按其ID排序。我应该对代码进行哪些更改?

1 个答案:

答案 0 :(得分:1)

只需执行以下操作:

    post = Product.objects.all().order_by("?")