【问题标题】:How to count and display objects in relation ManyToMany in Django如何在 Django 中计算和显示与 ManyToMany 相关的对象
【发布时间】:2010-12-18 21:54:38
【问题描述】:

我有一个包含新闻和类别的简单模型:

class Category(models.Model):
    name = models.CharField()
    slug = models.SlugField()

class News(models.Model):
    category = models.ManyToManyField(Category)
    title = models.CharField()
    slug = models.SlugField()
    text = models.TextField()
    date = models.DateTimeField()

我想统计每个类别的新闻并将其显示在网站上,如下所示:

Sport (5)
School (4)
Films (6)
Computer (2)
etc...

我该怎么做??

谢谢!

【问题讨论】:

    标签: python django django-models many-to-many


    【解决方案1】:

    查看 Django 1.1 中的 annotate() 函数。

    http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation

    示例(来自上述 URL):

    >>> q = Book.objects.annotate(num_authors=Count('authors'))
    >>> q[0].num_authors
    2
    >>> q[1].num_authors
    1
    

    【讨论】:

    • 我试过这个,但我得到了 AttributeError: 'Manager' object has no attribute 'annotate'
    • Category.objects.all().annotate(num_news = Count('news_set'))
    【解决方案2】:

    很简单:

    >>> for category in Category.objects.all():
    ...     print category.name, category.news_set.count()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 2013-10-20
      • 2015-06-01
      • 1970-01-01
      相关资源
      最近更新 更多