在 Django 中使用聚合
以下是我的模型:
class Story(models.Model):
author = models.ForeignKey(User, related_name='author_id', default=1)
source = models.ForeignKey(User, related_name='source_id', default=2)
User 是 django 提供的模型。
现在我需要找出每个用户创作和来源的文章数量。
我考虑将story_set与用户对象一起使用:
res = User.objects.annotate(Count('story_set'))
但是,故事中有两列引用用户。因此,Django 不知道该使用哪一个?
谁能帮我解决这个问题吗?
Following is my model:
class Story(models.Model):
author = models.ForeignKey(User, related_name='author_id', default=1)
source = models.ForeignKey(User, related_name='source_id', default=2)
User is the django provided model.
Now I need to find out number of articles authored and sourced by each user.
I thought of using story_set with user object:
res = User.objects.annotate(Count('story_set'))
However, there are two columns in story referencing User. Hence, Django won't know which one to use?
Can anyone help me on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
story_set
无论如何都不存在。如果您没有提供,这将是默认的lated_name
。既然你这样做了,你就必须使用它们。或者
所以,这就是 Django 知道差异的方式。
仅供参考:如果您使用了默认设置(因此您通过
.story_set.all()
访问故事,则不会使用“_set” “ 查询中的一部分。它只是Count('story')
。story_set
doesn't exist one way or another. That would've been the defaultrelated_name
if you hadn't provided one. Since you did, you have to use those.OR
So, that's how Django knows the difference.
FYI: if you had used the default (so you accessed stories via
.story_set.all()
, you don't use the "_set" part in queries. It would just beCount('story')
.django 让你指定一个
lated_name
的原因正是出于这个原因。你想要Count('author_id')
而不是Count('story_set')
(并且你应该给这些更好的名称,例如author_set
)the reason django makes you specify a
related_name
is exactly for this reason. you wantCount('author_id')
instead ofCount('story_set')
(and you should probably give these better names, e.g.author_set
)如果您希望在一个查询中同时获得作者文章数和来源文章数。您可能需要更合适的相关名称,例如“作者”和“来源”。
If you want both the number of authored and number of sourced articles in one query. You might want more appropriate related names, like "authored" and "sourced".