如何计数和显示与Django中的ManyToMany关系的对象 [英] How to count and display objects in relation ManyToMany in Django

查看:117
本文介绍了如何计数和显示与Django中的ManyToMany关系的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple model with news and categories:

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()

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

I want to count news for each category and display it on the website, like this:

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

我该怎么做?

谢谢! / p>

Thanks!

推荐答案

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

Check out annotate() function from Django 1.1.

a href =http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation =noreferrer> http://docs.djangoproject.com/en/dev /主题/ DB /汇聚/#主题-D b-aggregation

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

示例(从上面的URL):

Example (from that URL above):

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

这篇关于如何计数和显示与Django中的ManyToMany关系的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆