-
-
Save collinanderson/083c80186d6b3d23a2fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Matches(models.Model): | |
product_one = models.ForeignKey(Product, related_name = 'product_one') | |
product_two = models.ForeignKey(Product, related_name = 'product_two') | |
class MatchedProducts(APIView): | |
def get(self, request, *args, **kwargs): | |
product_id = kwargs.get('product_id') | |
matched_ids = [] | |
""" get direct matches """ | |
all_objs = Matches.objects.filter(Q(product_one_id = product_id) | Q(product_two_id = product_id)) | |
for obj in all_objs: | |
if obj.product_one.id not in matched_ids: | |
matched_ids.append(obj.product_one.id) | |
if obj.product_two.id not in matched_ids: | |
matched_ids.append(obj.product_two.id) | |
""" get matches from direct matches """ | |
while 1: | |
iterate = False | |
for obj_id in matched_ids: | |
all_objs = Matches.objects.filter(Q(product_one_id = obj_id) | Q(product_two_id = obj_id)) | |
for obj in all_objs: | |
if obj.product_one.id not in matched_ids: | |
matched_ids.append(obj.product_one.id) | |
iterate = True | |
if obj.product_two.id not in matched_ids: | |
matched_ids.append(obj.product_two.id) | |
iterate = True | |
if iterate == False: | |
break | |
all_products = [] | |
for prod_id in matched_ids: | |
all_products.append(Product.objects.get(pk = prod_id)) | |
serializer = ProductSerializer(all_products, many=True) | |
return Response(serializer.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment