我想在 Django 中显示最后 4 个产品

I want to show last 4 products in Django

数据库中有很多产品。但我只想显示 4 个最近添加的产品。

变量相似

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)

试试这个查询:

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

creation_date替换为用于存储Product实例创建日期的字段名称