Add a related articles section at the bottom of articles

This commit is contained in:
Gabriel Augendre 2020-12-31 13:51:13 +01:00
parent 86b7c280de
commit 843e3bfb0a
No known key found for this signature in database
GPG key ID: 1E693F4CE4AEE7B4
2 changed files with 33 additions and 0 deletions

View file

@ -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(",")))

View file

@ -17,4 +17,18 @@
{{ article.get_formatted_content|safe }}
</div>
</article>
{% if article.get_related_articles %}
<section>
<hr>
<h4>You might also like</h4>
{% for related in article.get_related_articles %}
<article>
<h5>
<a href="{% url "article-detail" slug=related.slug %}">{{ related.title }}</a>
</h5>
<p>{{ related.get_description }}</p>
</article>
{% endfor %}
</section>
{% endif %}
{% endblock %}