Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to show last 4 products in Django

There are many products in the database. but I only want to show the 4 most recently added products.

in the variable similar

views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def product_detail(request, category_slug, id):
category = Category.objects.all()
product = get_object_or_404(Product, category__slug = category_slug, id=id)
images = ProductImages.objects.filter(product_id=id)
similar = Product.objects.all().filter(category__slug=category_slug)
context = {
    'category': category,
    'product': product,
    'images': images,
    'similar': similar,
}

return render(request, 'detail.html', context)

>Solution :

Try this query:

similar = Product.objects.all().filter(category__slug=category_slug).order_by('-creation_date')[:4]

Replace creation_date with the name of the field used to store the creation date of a Product instance

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading