levi
levi

Reputation: 22697

Using own field to define others in Django Models

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')

Upvotes: 1

Views: 53

Answers (1)

karthikr
karthikr

Reputation: 99620

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.

Upvotes: 3

Related Questions