Home / Blogs

An Overview of Django Model Methods in 2023

Django
·

July 25, 2023

an-overview-of-django-model-methods-in-2023

Django, the popular Python web framework, provides developers with a powerful Object-Relational Mapping (ORM) tool known as Django Models. Models allow you to define the structure and behavior of your application’s data, and they come equipped with various built-in methods that make working with databases a breeze.

In this blog post, we’ll explore Django model methods with examples to demonstrate how they can simplify your development process and enhance the functionality of your applications.

str Method:

The __str__() method is a special method in Python that provides a string representation of an object. This method is commonly used in Django models to define a human-readable representation of an instance. Let’s take a look at an example:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.title} by {self.author}"

In the above example, the __str__() method is overridden to return a string representation of the Book object in the format “title by author”. This string representation is useful for displaying objects in the Django admin interface or when printing instances.

save Method:

The save() method is called when saving an instance of a model to the database. It allows you to perform custom logic before and after the save operation.  Lets explore an example:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    is_published = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if self.is_published:
            # Custom logic for published books
            # ...

        super().save(*args, **kwargs)  # Call the parent save() method

The save() method is overridden to add custom logic in the above example. If the is_published field is set to True, additional operations specific to published books can be performed before saving the instance.

delete Method:

The delete() method is called when deleting an instance of a model from the database. It allows you to perform additional cleanup or related operations before the deletion occurs. Let’s look at an example:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

    def delete(self, *args, **kwargs):
        # Custom logic before deleting the instance
        # ...

        super().delete(*args, **kwargs)  # Call the parent delete() method

In the above example, the delete() method is overridden to perform custom logic before deleting the Book instance. You can implement any additional actions that need to be taken when a book is deleted.

Custom Model Method:

Apart from the built-in model methods, Django allows you to define custom methods within your model classes. These methods can encapsulate business logic or perform calculations based on the instance’s attributes. Let’s see an example:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=5, decimal_places=2)

    def calculate_discounted_price(self, discount_percentage):
        discount_amount = self.price * (discount_percentage / 100)
        discounted_price = self.price - discount_amount
        return discounted_price

In the above example, we have defined a custom method called calculate_discounted_price() within the Book model. This method takes a discount_percentage parameter and calculates the discounted price by subtracting the discount amount from the original price. The discounted price is then returned.

To use this custom method, you can call it on a Book instance as follows:

book = Book.objects.get(pk=1)
discounted_price = book.calculate_discounted_price(10)
print(discounted_price)

In this example, we retrieve a Book object with a primary key of 1 from the database. We then call the calculate_discounted_price() method on the book instance, passing a discount percentage of 10. The method calculates and returns the discounted price, which is then printed.

Additionally, we have also overridden the __str__() method in the Book model to provide a human-readable representation of the model instance. In this case, it returns the title of the book.

Custom model methods in Django allow you to add custom behavior to your models and perform operations specific to your application’s requirements. Whether it’s performing complex calculations, manipulating data, or implementing custom business logic, custom model methods provide flexibility and extensibility to your Django models.

Conclusion:

Django model methods are a powerful tool for customizing the behavior of your models and adding business logic. By defining custom methods within your model classes, you can perform calculations, manipulate data, or implement custom functionality specific to your application’s needs. Understanding and utilizing these methods effectively will enhance the flexibility and extensibility of your Django projects. So, dive into the world of Django custom model methods, and unlock the full potential of your data-driven applications.

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.