def add_bought_with_relations_for_product(product_id, max_quantity=10):
 order_ids_to_check = OrderLine.objects.filter(product_id=product_id).values_list('order_id', flat=True)
 related_product_ids_and_quantities = OrderLine.objects.exclude(product_id=product_id).filter(type=OrderLineType.PRODUCT, order_id__in=set(order_ids_to_check)).values('product_id').annotate(total_quantity=Sum('quantity')).order_by('-total_quantity')[:max_quantity]
 for product_data in related_product_ids_and_quantities:
  ProductCrossSell.objects.create(product1_id=product_id, product2_id=product_data['product_id'], weight=product_data['total_quantity'], type=ProductCrossSellType.BOUGHT_WITH)

def add_bought_with_relations_for_product ( product_id , max_quantity = 10 ) : order_ids_to_check = OrderLine . objects . filter ( product_id = product_id ) . values_list ( 'order_id' , flat = True ) related_product_ids_and_quantities = OrderLine . objects . exclude ( product_id = product_id ) . filter ( type = OrderLineType . PRODUCT , order_id__in = set ( order_ids_to_check ) ) . values ( 'product_id' ) . annotate ( total_quantity = Sum ( 'quantity' ) ) . order_by ( '-total_quantity' ) [ : max_quantity ] for product_data in related_product_ids_and_quantities : ProductCrossSell . objects . create ( product1_id = product_id , product2_id = product_data [ 'product_id' ] , weight = product_data [ 'total_quantity' ] , type = ProductCrossSellType . BOUGHT_WITH )
add productcrosssell objects with type productcrossselltype .