Skip to content

Instantly share code, notes, and snippets.

Created January 16, 2015 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/0ca694ddc7f3c80fa2be to your computer and use it in GitHub Desktop.
Save anonymous/0ca694ddc7f3c80fa2be to your computer and use it in GitHub Desktop.
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