Kelvin Forde
Kelvin Forde

Reputation: 60

Using a list of objects in Django Template

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!

Upvotes: 1

Views: 1544

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

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)

Upvotes: 2

Related Questions