在 Django 中使用聚合

发布于 2024-12-20 04:41:16 字数 447 浏览 4 评论 0原文

以下是我的模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烂人 2024-12-27 04:41:16

story_set 无论如何都不存在。如果您没有提供,这将是默认的 lated_name。既然你这样做了,你就必须使用它们。

res = User.objects.annotate(Count('author_id'))

或者

res = User.objects.annotate(Count('source_id'))

所以,这就是 Django 知道差异的方式。

仅供参考:如果您使用了默认设置(因此您通过 .story_set.all() 访问故事,则不会使用“_set” “ 查询中的一部分。它只是 Count('story')

story_set doesn't exist one way or another. That would've been the default related_name if you hadn't provided one. Since you did, you have to use those.

res = User.objects.annotate(Count('author_id'))

OR

res = User.objects.annotate(Count('source_id'))

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 be Count('story').

御守 2024-12-27 04:41:16

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 want Count('author_id') instead of Count('story_set') (and you should probably give these better names, e.g. author_set)

薯片软お妹 2024-12-27 04:41:16
res = User.objects.annotate(num_authored=Count('author_id')).annotate(num_sourced=Count('source_id'))
res[0].num_authored
res[0].num_sourced

如果您希望在一个查询中同时获得作者文章数和来源文章数。您可能需要更合适的相关名称,例如“作者”和“来源”。

res = User.objects.annotate(num_authored=Count('author_id')).annotate(num_sourced=Count('source_id'))
res[0].num_authored
res[0].num_sourced

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".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文