Django: How to set a field's default value to the value of a field in a parent model -
say have following model
class sammich(models.model): name = models.charfield(max_length=200) ratio_of_cheese_to_meat = models.floatfield(default=0.3)
i'd able create new model has field pulls default ratio_of_cheese_to_meat of 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.
one option override model's save()
method , 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)
Comments
Post a Comment