Use of @property Decorator in Django Models

Estimated read time: 3 min

The @property decorator in Python is a powerful way to define read-only attributes in a Django model. It allows you to calculate or derive values dynamically without storing them in the database. This is particularly useful for calculated fields like a discounted price or selling price in an e-commerce application.

Let’s dive into how to use the @property decorator in Django models with a practical example.

Dynamic Price Calculation in Django Model with @property:

The @property decorator in Django models allows us to define dynamic, read-only attributes that are not stored in the database but are calculated on the fly. This is particularly useful for e-commerce applications where prices like discounted price and selling price are derived from the base price and discount.


Below is a Django model example showcasing how to calculate discounted price and selling price using the @property decorator.

Code Implementation:


    from django.db import models

    class Product(models.Model):
        name = models.CharField(max_length=255)
        base_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)
        discount = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)

        def __str__(self):
            return self.name

        @property
        def discounted_price(self):
            """
            discounted_price = (base_price * discount) / 100
            Example:
            If base_price = 600 and discount = 5,
            discounted_price = (600 * 5) / 100 = 30
            """
            return (self.base_price * self.discount) / 100

        @property
        def selling_price(self):
            """
            selling_price = base_price - discounted_price
            Example:
            If base_price = 600 and discounted_price = 30,
            selling_price = 600 - 30 = 530
            """
            return self.base_price - self.discounted_price

Detailed Explanation:

  1. Fields:

    • name: Represents the product name.
    • base_price: The original price of the product before discounts.
    • discount: The percentage of the discount applied to the product.
  2. Methods:

    • discounted_price:
      • Calculates the discount amount using the formula:
        discounted_price = (base_price * discount) / 100
      • Example:
        • If base_price is 600 and discount is 5, the discounted price will be:
          (600 * 5) / 100 = 30
    • selling_price:
      • Calculates the final price after applying the discount using the formula:
        selling_price = base_price - discounted_price
      • Example:
        • If base_price is 600 and discounted_price is 30, the selling price will be:
          600 - 30 = 530
  3. __str__ Method:

    • Returns the product's name, representation in Django admin or shell.
How to Access Property:


    product = Product.objects.create(
        name="Headphones", base_price=600.00, discount=5.00
    )

    print(product.name)
    Headphones

    print(product.base_price)
    # 600.00

    print(product.discount)
    # 5.00

    print(product.discounted_price)
    # 30.00

    print(product.selling_price)
    # 570.00


Advantages of Using @property
  1. Dynamic Calculation:

    • The discounted_price and selling_price are calculated only when accessed, ensuring they are always up to date.
  2. Avoid Data Redundancy:

    • No need to store derived values like discounted or selling prices in the database, keeping the schema clean.
  3. Centralized Logic:

    • All pricing-related calculations are encapsulated within the model, making it easier to update or debug.
  4. Improved Readability:

    • Accessing product.discounted_price feels like reading an attribute rather than calling a method.

Real-World Applications:

  • E-commerce Platforms:

    • Display calculated prices without storing them in the database.
    • Keep calculations consistent across templates, views, and APIs.
  • Reports and Analytics:

    • Derive real-time prices dynamically for dashboards and reports.

Conclusion:

By using the @property decorator, you can simplify the management of calculated fields in Django models. This approach ensures consistency, avoids redundant data storage, and keeps your code clean and maintainable.

The example of calculating discounted price and selling price in the Product model is a practical illustration of how the @property decorator can enhance the functionality of your Django models.

💫Thank you💫

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.