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


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)


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

Answered By – RedWheelbarrow

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published