From 843e3bfb0a31f82f341161bf7d74f791402cbb0d Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Thu, 31 Dec 2020 13:51:13 +0100 Subject: [PATCH] Add a related articles section at the bottom of articles --- articles/models.py | 19 +++++++++++++++++++ .../templates/articles/article_detail.html | 14 ++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/articles/models.py b/articles/models.py index 82efe13..9e494ee 100644 --- a/articles/models.py +++ b/articles/models.py @@ -1,3 +1,4 @@ +import random import re import uuid from functools import cached_property @@ -132,3 +133,21 @@ class Article(AdminUrlMixin, models.Model): if content: return readtime.of_html(content).minutes return 0 + + @cached_property + def get_related_articles(self): + related_articles = set() + for keyword in self.get_formatted_keywords: + potential_articles = Article.objects.filter( + keywords__icontains=keyword, + status=Article.PUBLISHED, + ).exclude(pk=self.pk) + for article in potential_articles: + if keyword in article.get_formatted_keywords: + related_articles.add(article) + sample_size = min([len(related_articles), 3]) + return random.sample(related_articles, sample_size) + + @cached_property + def get_formatted_keywords(self): + return list(map(lambda k: k.strip().lower(), self.keywords.split(","))) diff --git a/articles/templates/articles/article_detail.html b/articles/templates/articles/article_detail.html index a48fdd3..053c2ec 100644 --- a/articles/templates/articles/article_detail.html +++ b/articles/templates/articles/article_detail.html @@ -17,4 +17,18 @@ {{ article.get_formatted_content|safe }} + {% if article.get_related_articles %} +
+
+

You might also like

+ {% for related in article.get_related_articles %} + + {% endfor %} +
+ {% endif %} {% endblock %}