diff --git a/addons/website_forum/models/forum_forum.py b/addons/website_forum/models/forum_forum.py index 1bc89788b3f..a1153ce4a61 100644 --- a/addons/website_forum/models/forum_forum.py +++ b/addons/website_forum/models/forum_forum.py @@ -198,11 +198,13 @@ class Forum(models.Model): @api.depends('post_ids') def _compute_last_post_id(self): + last_forums_posts = self.env['forum.post']._read_group( + [('forum_id', 'in', self.ids), ('parent_id', '=', False), ('state', '=', 'active')], + groupby=['forum_id'], aggregates=['id:max'], + ) + forum_to_last_post_id = {forum.id: last_post_id for forum, last_post_id in last_forums_posts} for forum in self: - forum.last_post_id = forum.post_ids.search( - [('forum_id', '=', forum.id), ('parent_id', '=', False), ('state', '=', 'active')], - order='create_date desc', limit=1, - ) + forum.last_post_id = forum_to_last_post_id.get(forum.id, False) @api.depends('post_ids.state', 'post_ids.views', 'post_ids.child_count', 'post_ids.favourite_count') def _compute_forum_statistics(self): diff --git a/addons/website_forum/tests/test_forum_internals.py b/addons/website_forum/tests/test_forum_internals.py index 772edad458e..785239ecee9 100644 --- a/addons/website_forum/tests/test_forum_internals.py +++ b/addons/website_forum/tests/test_forum_internals.py @@ -59,6 +59,24 @@ class TestForumInternals(TestForumCommon): self.assertEqual(website_2.forum_count, 6, '6 global forums') + def test_website_forum_last_post_id(self): + """Check that each forum's last post is computed correctly and efficiently.""" + test_forums = self.base_forum | self.forum + new_posts = self.env["forum.post"].create([{ + 'name': f'New Post {forum_post_idx}', + 'forum_id': forum.id, + } for forum_post_idx, forum in enumerate(test_forums)]) + + with self.assertQueryCount(1): + self.assertEqual(test_forums.last_post_id.ids, new_posts.ids) + + another_post = self.env["forum.post"].create([{ + 'name': 'Another New Post', + 'forum_id': self.base_forum.id, + }]) + with self.assertQueryCount(1): + self.assertEqual(test_forums.last_post_id.ids, (another_post | new_posts[1]).ids) + @tagged('forum_internals') class TestPostInternals(TestForumCommon):