How to count and display objects in relation ManyToMany in Django

前端 未结 2 1151
无人共我
无人共我 2021-01-03 09:27

I have a simple model with news and categories:

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

class News(models.         


        
相关标签:
2条回答
  • 2021-01-03 10:08

    Very simple:

    >>> for category in Category.objects.all():
    ...     print category.name, category.news_set.count()
    
    0 讨论(0)
  • 2021-01-03 10:14

    Check out annotate() function from Django 1.1.

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

    Example (from that URL above):

    >>> q = Book.objects.annotate(num_authors=Count('authors'))
    >>> q[0].num_authors
    2
    >>> q[1].num_authors
    1
    
    0 讨论(0)
提交回复
热议问题