0

How to get a list of n no.of model entries from a model having m no.of entries

Indetail.....I have a model of 50 entries i want a query set of 6 ramdom entries from that 50 entries using built-in class based ListViews.

I am portfolio_list give me all the entries of model present but i need only random 6 entries for index list display.

views.py

class PortfolioListView(ListView):
    model = Portfolio
    template_name = 'portfolio/portfolio_index.html'

portfolio_list.html

{% block Body_Content %}
  {% for item in portfolio_list %}
    <div class="card-group">
      {% include "portfolio/_portfolio.html"  %}
    </div>
  {% endfor %}
{% endblock Body_Content %}

2 Answers 2

1

You can do this by setting it in the queryset attribute, for example:

from django.views.generic.list import ListView

class PortfolioListView(ListView):
    model = Portfolio
    queryset = Portfolio.objects.order_by('?')[:6]
    template_name = 'portfolio/portfolio_index.html'
Sign up to request clarification or add additional context in comments.

Comments

1

you can override get_queryset method to build your custom queryset.

def get_queryset(self):
    return Portfolio.objects.order_by('?')[:6]

Note: order_by('?') queries may be expensive and slow, depending on the database backend you’re using.

1 Comment

it work but as you said taking more time... anyway thanks

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.