1

This is my first time to ask a question on here so apologies if it isn't structured very well. Basically what I have is a Model called Product, which at the minute has 7 products. I am looking to pull out 3 random products from this Model and store them in a list, which I then want to access from a template to show the 3 objects which are now in the list.

My attempt at getting 3 random objects from the db:

 ## Finding 3 random products to show
        all_product_list = list(Product.objects.values_list('name', 'price', 'image'))
        checkout_products = list()
        counter = 3
        num_products = len(all_product_list)

        while counter!= 0:
            random_prod = random.randint(0, num_products - 1)
            checkout_products.append(all_product_list[random_prod])
            counter -= 1

Then in my template I am trying to access as follows:

{% for checkout_prod in checkout_products %}
                    <div class="col text-light">
                        {{ checkout_prod.price }}
                    </div>
{% endfor %}

I am also rendering the list at the end of my function as follows :

return render(request, 'cart.html', {'cart_items':cart_items, 'total':total, 'counter':counter,
                                        'data_key': data_key, 'stripe_total':stripe_total,
                                        'description':description, 'before_discount':before_discount,
                                        'difference': difference, 'checkout_products': checkout_products,})

I am not getting any error, but there is nothing at all showing on the page, any help with this would be greatly appreciated.

Thank You!

1
  • By using .values_list, you no longer have object,s but only a 3-tuple, hence checkout_p\rod does not contain an attribute .product, only a checkout_prod.1, will give the price. Commented Dec 2, 2020 at 11:21

1 Answer 1

2

I think the main problem here is the use of .values_list(…) [Django-doc] this will produce a QuerySet that wraps tuples, not model object, so .price does no longer exists.

But you do not need to use .values_list(…) in the first place, you can simply fetch the model objects and use random.sample(…) [python-doc] to obtain three elements:

from random import sample

all_product_list = Product.objects.all()
counter = 3
checkout_products = sample(all_products_list, counter)
Sign up to request clarification or add additional context in comments.

Comments

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.