在主页中显示count和top_categories

时间:2017-09-21 08:18:35

标签: python django python-3.x django-models django-views

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

texts = response.xpath('//li[@class="container list-display-box__list__container"]/div/div/div/div/div[@class="shipping"]/p//text()')

if len(texts) > 1:
   data = texts[1].extract()
elif len(text) == 1:
   data = texts[0].extract()
else
   data ="Not found"

现在有一个混乱,我是否必须在类别模式中实现top_categories函数或我正在做的方式是好的?因为在主页中显示内容的工作是家庭视图的作用。

3 个答案:

答案 0 :(得分:1)

您可以在 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 %}

答案 1 :(得分:0)

好吧我想我会做这样的事情:

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

    @staticmethod
    def top_category():
        return models.Count('categories')).order_by('-categories_count')

使它成为一个静态方法,因为它不是一个实例。更好的方法是扩展类别管理器并向其添加方法get_top_category,以便您可以调用Category.objects.get_top_category()。然后在产品型号中调用它:

   def top_products(self):
        count_category = Category.top_category() # or Category.objects.get_top_category() if you have done it this way
        product = Product.objects.values('id').annotate(count_category)
        return product

一些doc to override managers

答案 2 :(得分:0)

我建议你使用templatetags,因为如果你用views处理这种情况,你将为另一个页面创建类似的流行过滤器。

# yourapp/templatetags/popcategories.py

from django import template
from yourapp.models import (Category, Product)

register = template.Library()

@register.assignment_tag
def popular_categories():
    categories = Category.objects.all()
    get_total = lambda c: Product.objects.filter(categories__slug=c.slug).count()
    tags_list = [{'category': category, 'total': get_total(category)} for category in categories]
    tags_list.sort(key=lambda x: int(x['total']), reverse=True)
    return tags_list[:10] # return 10 top

然后,您可以在模板company/home.html中使用它;

{% load popcategories %}
{% popular_categories as categories_list %}
{% for category in categories_list %}
  <a href="">
    {{ category.name }} - {{ category.slug }}
  </a>
{% empty %}
  <p>No categories yet!</p>
{% endfor %}