django admin中的其他依赖字段

时间:2016-10-17 08:54:33

标签: django django-admin

我有一个模特

class Essai_Fluage(models.Model):
    name = models.ForeignKey(Material, verbose_name=_('name'))
    elongation= models.FloatField(_('allongement'),blank=True, null=False)
    t_02 = models.IntegerField(_('t_0.2%'),blank=True, null=False)
    t_05 = models.IntegerField(_('t_0.5%'),blank=True, null=False)
    t_075 = models.IntegerField(_('t_0.75%'),blank=True, null=False)
    tr = models.IntegerField(_('tr'),blank=True, null=False)
    T= models.FloatField(_('temperature'),blank=True, null=False)
    sigma = models.FloatField(_('contrainte'),blank=True, null=False)
    PLM = models.FloatField(_('PLM'),blank=True, null=False)
    rep = models.IntegerField(_('indice'),blank=True, null=True)

    def __unicode__(self):
        return '%s'  % (self.name)

    class Meta:
        verbose_name = _('creep test')
        verbose_name_plural = _('creep test')

    ordering = ['rep',]

我想让PLM字段用公式计算 PLM =(T / 1000)*(20 + log10(tr))

T和tr是字段

T= models.FloatField(_('temperature'),blank=True, null=False)
tr = models.IntegerField(_('tr'),blank=True, null=False)
管理员中的

是否可以这样做?

1 个答案:

答案 0 :(得分:0)

您可以覆盖模型的保存方法以计算公式中的值。

试试这个:

    class Essai_Fluage(models.Model):
        name = models.ForeignKey(Material, verbose_name=_('name'))
        elongation= models.FloatField(_('allongement'),blank=True, null=False)
        t_02 = models.IntegerField(_('t_0.2%'),blank=True, null=False)
        t_05 = models.IntegerField(_('t_0.5%'),blank=True, null=False)
        t_075 = models.IntegerField(_('t_0.75%'),blank=True, null=False)
        tr = models.IntegerField(_('tr'),blank=True, null=False)
        T= models.FloatField(_('temperature'),blank=True, null=False)
        sigma = models.FloatField(_('contrainte'),blank=True, null=False)
        PLM = models.FloatField(_('PLM'),blank=True, null=False)
        rep = models.IntegerField(_('indice'),blank=True, null=True)

        def __unicode__(self):
            return '%s'  % (self.name)

        class Meta:
            verbose_name = _('creep test')
            verbose_name_plural = _('creep test')

        ordering = ['rep',]

        def save(self, *args, **kwargs):
            if self.PLM is not None:
                self.PLM = (self.T/1000)*(20 + log10(self.tr))
                super(Essai_Fluage, self).save(*args, **kwargs)