Cast count to float before dividing

`COUNT` returns a `bigint`, which can't be divided into a float
This commit is contained in:
Jake Howard 2023-06-02 17:34:10 +01:00
parent ef20d9c695
commit 033b8be859
Signed by: jake
GPG key ID: 57AFB45680EDD477

View file

@ -2,6 +2,7 @@ from typing import Any, Optional, Type
from django.contrib.postgres.search import TrigramSimilarity from django.contrib.postgres.search import TrigramSimilarity
from django.db import models from django.db import models
from django.db.models.functions import Cast
from django.utils import timezone from django.utils import timezone
from django.utils.functional import cached_property from django.utils.functional import cached_property
from modelcluster.fields import ParentalManyToManyField from modelcluster.fields import ParentalManyToManyField
@ -84,7 +85,11 @@ class BlogPostPage(BaseContentPage):
page_tags = list(self.tags.values_list("id", flat=True)) page_tags = list(self.tags.values_list("id", flat=True))
similar_posts = similar_posts.annotate( similar_posts = similar_posts.annotate(
# If this page has no tags, ignore it as part of similarity # If this page has no tags, ignore it as part of similarity
tag_similarity=models.Count("tags", filter=models.Q(tags__in=page_tags)) # NB: Cast to a float, because `COUNT` returns a `bigint`.
tag_similarity=Cast(
models.Count("tags", filter=models.Q(tags__in=page_tags)),
output_field=models.FloatField(),
)
/ len(page_tags) / len(page_tags)
if page_tags if page_tags
else models.Value(1) else models.Value(1)