gpt4 book ai didi

python - 在主页显示计数和 top_categories

转载 作者:太空宇宙 更新时间:2023-11-04 04:58:50 24 4
gpt4 key购买 nike

我想在首页显示top_categories。我编写了 top_categories 函数来列出产品数量最多的类别。但是我已经在产品模型中编写了这个功能。我很困惑我应该在哪里写这个。这是我的代码

class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)

class Product(models.Model):
name = models.CharField(max_length=200, unique=True,
blank=False, null=False)
categories = models.ManyToManyField(Category, related_name='products')

def top_categories(self):
product = Product.objects.values('id').annotate(
categories_count=models.Count('categories')).order_by('-categories_count')
return product

def home(request):
categories = Category.objects.all()
companies = Company.objects.all()[:12]
context = {
'categories': categories,
'companies': companies
}
return render(request, 'company/home.html', context)

现在有一个困惑,我是否必须在类别模态中实现 top_categories 函数,或者我的做法是否合适?因为展示首页内容的工作就是首页 View 的作用。

最佳答案

您可以在 views.py

中完成
def home(request):
# arrange your category on basis of product_count
categories = Category.objects.annotate(product_count = Count('products')).order_by('-product_count')
# if you want only top 10 categories
# categories = categories[:10]
companies = Company.objects.all()[:12]
context = {
'categories': categories,
'companies': companies
}
return render(request, 'company/home.html', context)

home.html

{% for category in categories %} 
<h3> category name:</h3>{{category.name}}
<h3> Total product::</h3>{{category.product_count}}
{% endfor %}

关于python - 在主页显示计数和 top_categories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46338836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com