get related products exclude duplicates

This commit is contained in:
Diego Calvo
2021-03-29 15:03:42 +02:00
parent 16f41bfa57
commit ca3566121e

View File

@@ -91,35 +91,40 @@ def get_related_products(product):
""" """
total_results = [] total_results = []
ids = []
# search by category # 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 # add to results
for item in category_qs: for item in category_qs:
total_results.append(item) total_results.append(item)
ids.append(item.id)
# check size # check size
if len(total_results) < 10: if len(total_results) < 10:
# search by tags # 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 # add to results
for item in tags_qs: for item in tags_qs:
total_results.append(item) total_results.append(item)
ids.append(item.id)
# check size # check size
if len(total_results) < 10: if len(total_results) < 10:
# search by coop # 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 # add to results
for item in coop_qs: for item in coop_qs:
total_results.append(item) total_results.append(item)
ids.append(item.id)
# check size # get non related products. not necessary
if len(total_results) < 10: # if len(total_results) < 10:
# search by latest # # search by latest
latest_qs = Product.objects.order_by('-created')[:10] # latest_qs = Product.objects.order_by('-created').exclude(pk__in=ids)[:10]
# add to results # # add to results
for item in coop_qs: # for item in latest_qs:
total_results.append(item) # total_results.append(item)
return total_results[:10] return total_results[:10]