Answer the question
In order to leave comments, you need to log in
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])
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question