Creating a model function - 30 days of Django

Creating a model function - 30 days of Django

/ #Django


A common practice in Django is making fat models and thin views. Keep reading to learn more.

We generally want to have as simple views as possible, because it doesn't make sense to put functionality there. Functionality should be put in model files or utility files.

So in this part of the series, we will add a custom function to one of our models. Open up "category/models.py":

class Category(models.Model):
    title = models.CharField(max_length=255)
    
    class Meta:
        verbose_name_plural = 'Categories'
        
    def __str__(self):
        return self.title
        
    def number_of_tasks(self):
        return self.tasks.count()

As you can see here, we've added a new method to the Category model. This could now be used in templates and similar like this:

{{ category.number_of_tasks }}

Table of contents

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.