Home > database >  I want to show last 4 products in Django
I want to show last 4 products in Django

Time:04-02

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

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)

CodePudding user response:

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

  • Related