Skip to main content
 首页 » 编程设计

python之在主页显示计数和 top_categories

2025年02月15日7lhb25

我想在首页显示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 %}