Brian
Brian

Reputation: 1819

Django: How to set a field's default value to the value of a field in a parent model

Say I have the following model

class Sammich(models.Model):
    name = models.CharField(max_length=200)
    ratio_of_cheese_to_meat = models.FloatField(default=0.3)

I'd like be able to create a new model that has a field which pulls its default from ratio_of_cheese_to_meat of the Sammich class

class DeliSammich(models.Model):
    sammich = models.ForiegnKey(Sammich)
    type_of_meat = models.CharField(max_length=200)
    type_of_cheese = models.CharField(max_length=200)
    ratio_of_cheese_to_meat = models.FloatField(default=Sammich.objects.get(pk=sammich.id).ratio_of_cheese_to_meat)

Which isn't working.

Upvotes: 2

Views: 565

Answers (2)

alecxe
alecxe

Reputation: 473803

One option would be to override the model's save() method and get the default:

class DeliSammich(models.Model):
    sammich = models.ForeignKey(Sammich)
    type_of_meat = models.CharField(max_length=200)
    type_of_cheese = models.CharField(max_length=200)
    ratio_of_cheese_to_meat = models.FloatField()

    def save(self, *args, **kwargs):
        if not self.ratio_of_cheese_to_meat:
            self.ratio_of_cheese_to_meat = self.sammich.ratio_of_cheese_to_meat
        super(DeliSammich, self).save(*args, **kwargs)

Upvotes: 4

Aaron Lelevier
Aaron Lelevier

Reputation: 20770

You could solve that using a Global Variable. If you used a Global Variable, your models.py would look like this:

DEFAULT_SAMMICH = 0.3

class Sammich(models.Model):
    name = models.CharField(max_length=200)
    ratio_of_cheese_to_meat = models.FloatField(default=DEFAULT_SAMMICH)

class DeliSammich(models.Model):
    sammich = models.ForiegnKey(Sammich)
    type_of_meat = models.CharField(max_length=200)
    type_of_cheese = models.CharField(max_length=200)
    ratio_of_cheese_to_meat = models.FloatField(default=DEFAULT_SAMMICH)

Upvotes: -1

Related Questions