Zorgan Zorgan - 2 months ago 11
Python Question

How to set the value of a model field by performing an equation between other model fields

I want to set the value of a model field by performing an equation between other model fields. Here's my model:

class Current(models.Model):
time = models.IntegerField(default=0)
post_score = models.ForeignKey(PostScore, blank=True, null=True)
comment_score = models.ForeignKey(CommentScore, blank=True, null=True)


Say I want to create a new field called
rate
, which is calculated by:

(post_score + comment_score) / time


Is this possible?

Answer

Something like this:

models.py

class Current(models.Model):
    ....

    def get_current_rate(self):
        return (self.post_score + self.comment_score) / self.time

In views.py:

from mymodels import Current

def someview():
    ....
    rate = Current.get_current_rate()