'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
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 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RedWheelbarrow |
