1

If I want to set a default value in a field and that value is derived from another field from same model. How can do something like that:

class MyModel(models.Model):
     field_1 = models.CharField()
     field_2 = models.Charfield(defualt=field_1 + 'extra info')

1 Answer 1

3

You cannot use the default in this case. You can use the model's save method for this purpose:

class MyModel(models.Model):
    field_1 = models.CharField(max_length=80)
    field_2 = models.Charfield(max_length=80)

    def save(self, *args, **kwargs):
        #Here you can have all kinds of validations you would need

        self.field_2 = self.field_1 + "extra info"
        super(MyModel, self).save(*args, **kwargs)

Now, you can hide/exclude the field_2 from the forms/modelforms if you choose to.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.