How to get cost per item from line item list in shopify using python api - Existing solution is slow

Aswinth_Raj1
New Member
1 0 0

Hi, 

I am trying to fetch cost per item (buying price) from the list of line items using python Shopify API. My aim to calculate the margin made per order and was able to do it with the below approach 

current_order = shopify.Order.find(3279415017656) #using a single order id for testing 

order_name = current_order.name
order_subtotal = float(current_order.subtotal_price)
order_shipNcod_cost = (float(current_order.total_price) - float(order_subtotal))

order_line_item_list = current_order.line_items #get the items in the order

print (order_name, order_subtotal, order_shipNcod_cost)

COGS_list=[]
#Calculate COGS per order
for items in order_line_item_list:
product_variant_id = shopify.Variant.find(items.variant_id)

# GET Buy price for this product
product_inventory_id_number = product_variant_id.inventory_item_id
product_inventory_id = shopify.InventoryItem.find(product_inventory_id_number)
Unit_Buy_Price = product_inventory_id.cost # Get Cost from product inventory ID
Buy_Price = float (Unit_Buy_Price) * int(items.quantity)
COGS_list.append(Buy_Price)


COGS_per_order = sum(COGS_list)
print ("COGS for this order =", COGS_per_order)

Profit_per_order = order_subtotal - COGS_per_order
print ("Profit for this order =", Profit_per_order)

Margin_per_order = (Profit_per_order/order_subtotal)*100
print ("Margin for this order =", Margin_per_order)

 

However, the above method is very slow because I am using shopify.find to find the inventory ID and variant ID. So what can be done to speed this up 

In this (https://shopify.dev/docs/themes/liquid/reference/objects/line_item#line_item-product) line_item documentation there is a way to get line_item.variant directly without having to use line_item.variant_id and then search for it using shopify.find. But it is not working for some reason 

Meaning 

product_variant_id = line_item.variant_id #IS WORKING
product_variant = line_item.variant #IS NOT WORKING
0 Likes