Kazz
Kazz

Reputation: 616

Django model field with default value from another model

I have a model like this:

class ModelA(models.Model):
    foo = models.CharField(max_length=255)
    bar = models.CharField(max_length=255)

Now i wanna have something like this:

class ModelB(models.Model):
    aaa = models.ForeignKey(ModelA)
    tar = models.Char(Field(max_length=255, default="")
    fo2 = models.CharField(max_length=255, default=???)

where i want fo2 to take a value from ModelA unless other is provided.

How should i do that?

Upvotes: 8

Views: 4559

Answers (1)

NS0
NS0

Reputation: 6106

Do you want the default value of fo2 to equal to something related with the specific instance of aaa at creation?

The way to do that would be to override the save method

class ModelB(models.Model):
    aaa = models.ForeignKey(ModelA)
    tar = models.Char(Field(max_length=255, default="")
    fo2 = models.CharField(max_length=255)

    def save(self, *args, **kwargs):
        if self.fo2 is None:
            self.fo2 = self.aaa._value_taken_from_Model_A
        super(ModelB, self).save(*args, **kwargs)

Upvotes: 10

Related Questions