Open In App

How to Set a Django Model Field’s Default Value to a Function or Callable

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In Django, models are the essential components that define the structure of our database tables. Each field in a model corresponds to a column in the database, and we can specify various options for these fields, such as their type, whether they can be null, and their default values. Setting a default value can be simple when it’s static (like a number or string), but what if we need it to be dynamically generated, such as a timestamp or a unique identifier? This is where callable functions come in.

For Example:

Python
from django.db import models
import shortuuid

class Product(models.Model):
  	uuid = models.CharField(max_length=36, default=shortuuid.uuid)
    name = models.CharField(max_length=100, default="GFG User")
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)

Here, shortuuid.uuid method is called each time a new instance is created.

Note: When setting a callable as the default value, we must pass the name of the function and not call it. Django will call that function to set the default value whenever an instances is created.

Set Default Values in Django using Callable/Functions

When defining model fields in Django, we can provide a default value. This value is automatically assigned to the field when no other value is specified. Here's a simple example:

Python
from django.db import models

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

In this case, if no price is provided when a new Product is created, it will default to 0.0.

However, sometimes static default values aren't enough. For instance, we may need to set the current date and time as a default value for a created_at field or generate a random string for an identifier. In such cases, Django allows us to set the default to a callable function.

Set a Django Model Field’s Default Value to a Function Call / Callable

A callable is any Python object that can be called like a function. In Django, you can assign a callable to the default parameter for a model field, which allows you to execute a function each time a new object is created.

For example, we can set the default value of a created_at field to the current timestamp by using Python's datetime module.

Let’s create a Django project to see how callable defaults work.

Install Django and Create a New Project

First, create a new Django project and an app:

django-admin startproject dynamic_defaults
cd dynamic_defaults
python manage.py startapp store

Add store in settings.py file app name.

Python
INSTALLED_APPS = [
    # ...,
    'store'
]

Now, we’ll modify our models.py to demonstrate using callables as default values.

Define the Model with Callable Defaults

In the store/models.py file, we’ll define a model Order that will use callable functions to generate dynamic default values.

Explanation:

  • generate_unique_id(): This function generates a unique identifier using uuid4(), which returns a random UUID.
  • auto_add_now=True: Django uses this Boolean to set the value whenever a new instance is created.
  • order_id: The default value is generated by the generate_unique_id() function, ensuring that each order has a unique identifier.
  • created_at: The default value is set to the current timestamp when the order is created.
Python
from django.db import models
import uuid
from datetime import datetime

# Callable function to generate unique identifier
def generate_unique_id():
    return str(uuid.uuid4())

class Order(models.Model):
    order_id = models.CharField(max_length=36, default=generate_unique_id)
    created_at = models.DateTimeField(auto_now_Add=True)
    product_name = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField(default=1)

    def __str__(self):
        return f"Order {self.order_id} for {self.product_name}"

Apply Migrations

After defining the model, run the following commands to create the necessary database tables:

python manage.py makemigrations
python manage.py migrate

Create Orders to See Callable Defaults in Action

Now that the database schema is ready, let's create some Order objects using the Django shell to see how the callable defaults work.

Open the shell:

python manage.py shell

In the shell, we’ll create an order without specifying the order_id or created_at fields. Since we set these fields to use callable defaults, Django will automatically populate them:

Python
from store.models import Order

# Create an order without specifying order_id or created_at
order = Order(product_name='Laptop', quantity=2)
order.save()

print(order.order_id)
print(order.created_at)

As we can see, Django successfully calls the functions to populate the fields with dynamic values.

call
Django Shell Output

Set a Callable Class as the Default Value in Django Model

In addition to functions, we can also use callable classes to set default values. Here's an example using a class-based callable:

Python
class DefaultQuantity:
    def __call__(self):
        return 10

class Order(models.Model):
    order_id = models.CharField(max_length=36, default=generate_unique_id)
    created_at = models.DateTimeField(auto_now_add=True)
    product_name = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField(default=DefaultQuantity())

In this case, DefaultQuantity is a class with a __call__() method. Django will execute the __call__() method to get the default value for the quantity field, which will be 10.

Testing the Callable Class

In the Django shell, create a new order:

Python
order = Order(product_name='Phone')
order.save()

print(order.quantity) 
Set default value to django model field

Conclusion

Setting default values in Django models is a common requirement, but dynamic defaults require a little more flexibility. By using callable functions or classes, you can generate dynamic default values such as unique identifiers, timestamps, or even complex logic that depends on external factors. This method is highly powerful and adds a great level of flexibility when designing Django models.


Practice Tags :

Similar Reads