A
A
AliminVerckon2020-07-20 13:21:52
Django
AliminVerckon, 2020-07-20 13:21:52

How to display random entries in a certain amount in django using the random module?

class ProductView(ListView):
  model = Products
  queryset = Products.objects.filter(draft = False)
  template_name = "products/index.html"


how to change this view so that four random records from the model are displayed using the random module

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2020-07-20
@AliminVerckon

something like this:

max_id = Products.objects.filter(draft=False).aggregate(max_id=Max("id"))['max_id']
random_products = []

if Products.objects.filter(draft=False).count() < 4:
    raise Exception('Мало объектов для выборки')

while len(random_products) < 4:
    pk = random.randint(1, max_id)
    if pk in random_products:
          continue
    product = Products.objects.filter(draft=False, pk=pk).first()
    if product:
          random_products.append(product)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question