Categories
Python Answers

How to set Model Field Default Based Off Another Field in Same Model with Python Django?

Spread the love

To set Model Field Default Based Off Another Field in Same Model with Python Django, we can override the save method to set the default value.

For instance, we write

def save(self, *args, **kwargs):
    if not self.subject_init:
        self.subject_init = self.subject_initials()
    super(Subject, self).save(*args, **kwargs)

to add the save method to a model class.

In it, we set the default value of the subject_init field to the result returned by self.subject_initials().

And then we call the super class’ save method with the arguments from the parameters.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *