Add discount on each product based on product price

I saw this question on Magento StackExchange:

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.

We can use a ProductSearch retrieve these products as Product objects using by_skulist()

>>> skus = [f"test_sku{n}" for n in range(1, 101)]
>>> products = api.products.by_skulist(skus)

To retrieve the Product objects using a field other than sku, like product_id, we can use by_list():

>>> 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))

We loop through our list of products and

  1. Skip the products if the price is not $100 or more

  2. Calculate the discount percentage by dividing the price by 1000

  3. Calculate the new, discounted product price by multiplying the current price by 1 - discount

  4. Use the new price we calculated to update the special_price of the product