【发布时间】:2011-10-11 07:58:58
【问题描述】:
假设我有一个简单的论坛模型:
class User(models.Model):
username = models.CharField(max_length=25)
...
class Topic(models.Model):
user = models.ForeignKey(User)
...
class Post(models.Model):
user = models.ForeignKey(User)
...
现在假设我想查看用户子集的每个用户有多少主题和帖子(例如,他们的用户名以“ab”开头)。
因此,如果我对每个帖子和主题进行一次查询:
User.objects.filter(username_startswith="ab")
.annotate(posts=Count('post'))
.values_list("username","posts")
产量:
[('abe', 5),('abby', 12),...]
和
User.objects.filter(username_startswith="ab")
.annotate(topics=Count('topic'))
.values_list("username","topics")
产量:
[('abe', 2),('abby', 6),...]
但是,当我尝试同时注释两者以获得一个列表时,我得到了一些奇怪的东西:
User.objects.filter(username_startswith="ab")
.annotate(posts=Count('post'))
.annotate(topics=Count('topic'))
.values_list("username","posts", "topics")
产量:
[('abe', 10, 10),('abby', 72, 72),...]
为什么主题和帖子会成倍增加?我预料到了:
[('abe', 5, 2),('abby', 12, 6),...]
获得正确列表的最佳方法是什么?
【问题讨论】:
标签: django annotations count django-queryset