From ca3566121e704c5d90d1087ef6852ab32670b7b9 Mon Sep 17 00:00:00 2001 From: Diego Calvo Date: Mon, 29 Mar 2021 15:03:42 +0200 Subject: [PATCH] get related products exclude duplicates --- products/utils.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/products/utils.py b/products/utils.py index 3f69ded..58af693 100644 --- a/products/utils.py +++ b/products/utils.py @@ -91,35 +91,40 @@ def get_related_products(product): """ total_results = [] + ids = [] + # search by category - category_qs = Product.objects.filter(category=product.category)[:10] + category_qs = Product.objects.filter(active=True, category=product.category)[:10] # add to results for item in category_qs: total_results.append(item) + ids.append(item.id) # check size if len(total_results) < 10: # search by tags - tags_qs = Product.objects.filter(tags__in=product.tags.all())[:10] + tags_qs = Product.objects.filter(active=True, tags__in=product.tags.all()).exclude(pk__in=ids)[:10] # add to results for item in tags_qs: total_results.append(item) + ids.append(item.id) # check size if len(total_results) < 10: # search by coop - coop_qs = Product.objects.filter(company=product.company)[:10] + coop_qs = Product.objects.filter(active=True, company=product.company).exclude(pk__in=ids)[:10] # add to results for item in coop_qs: total_results.append(item) + ids.append(item.id) - # check size - if len(total_results) < 10: - # search by latest - latest_qs = Product.objects.order_by('-created')[:10] - # add to results - for item in coop_qs: - total_results.append(item) + # get non related products. not necessary + # if len(total_results) < 10: + # # search by latest + # latest_qs = Product.objects.order_by('-created').exclude(pk__in=ids)[:10] + # # add to results + # for item in latest_qs: + # total_results.append(item) return total_results[:10]