P
P
Postalus2015-04-30 07:08:05
Django
Postalus, 2015-04-30 07:08:05

Is it possible to implement field value calculation directly in the model?

Citizens experts, there was such question. I have a need to create a model in which the values ​​of some fields will be calculated based on the values ​​of other fields. Here's how I implemented it (the example is simplified, but conveys the essence):

class Zzz(Superclass):
    aaa = models.ForeignKey(Aaa)
    bbb = models.ForeignKey(Bbb)
    ccc = models.ForeignKey(Ccc)

    @property
    def eee(self):
        return self.aaa, self.bbb, self.ccc

    @property
    def ddd(self):
        return reduce((lambda x, y: x + y), [e.some_param for e in self.eee])

Do I understand correctly that the value of ddd will be recalculated with each new access? Is it possible to remake the model code so that the field value is calculated once when creating a record, and then simply read from the database? Or is the only option - views?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
marazmiki, 2015-04-30
@Postalus

It is possible to alter something, but then this field will have to be added to the scheme. And fill on save:

class Zzz(Superclass):
    aaa = models.ForeignKey(Aaa)
    bbb = models.ForeignKey(Bbb)
    ccc = models.ForeignKey(Ccc)
    # Объявили поле и на всякий случай запретили редактировать его из админки или через форму.
    ddd = models.IntegerField(editable=False, default=0) 

    @property
    def eee(self):
        return self.aaa, self.bbb, self.ccc

    def save(self, *args, **kwargs):
        # Непосредственно перед физическим сохранением вычисляем значение поля
        self.ddd = reduce((lambda x, y: x + y), [e.some_param for e in self.eee])
        return super(Zzz, self).save(*args, **kwargs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question