Add discount on each product based on product price
Question
Question
I have 100 products in my store and each product has different price. I want to add discount on each product based on specific price. For example, If a product is added into the cart and it has 100usd price then i want to apply 10% discount on it and if a product is added into the cart and it has 110usd price then i want to apply 11% discount on it and so on. I hope you understand what I want to achieve. in simple words, discount on each product based on product price. Thanks
Solution Using MyMagento
First, you’ll want to Get a Magento 2 REST API Token With MyMagento
import magento
api = magento.get_api()
Let’s say we have the skus of the 100 products in an array
skus = [f"test_sku{n}" for n in range(1, 101)]
We can use a ProductSearch
retrieve products by_sku()
or by_skulist()
products = api.products.by_skulist(skus)
To retrieve the Product
objects using a field other than sku
, like product_id
for example, use the by_list()
method
product_ids = list(range(1,101))
products = api.products.by_list(
field="entity_id", # To search by product_id
values=product_ids
)
Once we have our list of Product
objects, we can calculate the discount based on their price, then update the special_price
(discount price) using the Product.update_special_price()
method
for product in products:
if product.price < 100:
continue
discount = product.price / 1000
price = product.price * (1 - discount)
product.update_special_price(round(price, 2))