Skip to content Skip to sidebar Skip to footer

Can A Django Model Field's Default Value Be Defined By A Function Dependent On A Foreign Parent Model?

I'm trying to have the default value of Report's fee be based on a parent model's attributes. I don't want to do this in save(), because the field needs to be presented to the user

Solution 1:

Your last example could potentially work with some work:

  1. First all, you need to __init__ on your class, not models.Model
  2. You need to set your attribute after the model has been initialized
  3. You need check if the model has been saved, or else your model will revert to the overridable fee every time you load it.

-

classJob(models.Model):
    veryImportant = models.IntegerField()
    defget_fee():
        return2 * veryImportant

classReport(models.Model):
    job = models.ForeignKey(Job)
    overridableFee = models.DecimalField(max_digits=7, decimal_places=2)
    def__init__(self, *args, **kwargs):
        super(Report, self).__init__(*args, **kwargs)
        ifnotself.id:self.overridableFee = self.job.get_fee() 

Post a Comment for "Can A Django Model Field's Default Value Be Defined By A Function Dependent On A Foreign Parent Model?"