Alberto Sordi
Alberto Sordi

Reputation: 25

Arithmetic operations between Django fields belonging to the same class model. Is it possible?

I have the need to divide a class field (Value) in Django-admin model with a fixed value (coefficient) in the same class. The result of this operation should populate another field (Points) of the same class. Both values are of same type (integers).

For example a user enter a value of '180', then he leaves coefficient to its default '10'. When it saves the new entry it should show up Points = 18

So for the moment I defined 'coefficient' field in Django models.py which defaults to 10. 'Value' field is editable as I said above. I thought to use F() to perform math operations between fields however I am not sure if this is the correct tool or there's something simpler. When I set up the following expression on my model I see alot complaints when I make db migrations.

Points = Visits.objects.all().annotate(div=F('Value') / F('Coefficient'))

Since I am new to Django I appreciate any help on this, maybe I am misunderstanding something obvious.

Upvotes: 2

Views: 731

Answers (2)

JPG
JPG

Reputation: 88689

Method-1

Override save() method of Value model, as

class Visits(models.Model):
    value = models.IntegerField()
    coefficient = models.IntegerField()
    points = models.IntegerField(blank=True, null=True, editable=False)

    def save(self, *args, **kwargs):
        self.points = int(self.value / self.coefficient)
        super().save(*args, **kwargs)


Method-2

use @property decorator

class Visits(models.Model):
    value = models.IntegerField()
    coefficient = models.IntegerField()

    @property
    def points(self):
        return int(self.value / self.coefficient)

Upvotes: 2

Thomas
Thomas

Reputation: 182093

You can simply override the save() method of your model to calculate the Points field:

    def save(self, *args, **kwargs):
        self.Points = self.Value / self.Coefficient
        super().save(*args, **kwargs)

You might also want to check for and handle division by zero here.

Upvotes: 0

Related Questions