Answer the question
In order to leave comments, you need to log in
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"
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question