Saif eldeen Adel
Saif eldeen Adel

Reputation: 388

How do i create a field in my model whose value is calculated using values from other fields?

I have a model that takes in 3 integers as part of its fields

class TradeBill(models.Model):
    ......
    first = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)])
    second = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)])
    third = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)])
    .....

What I need to have is another positive integer field called score that adds up the value of the other three. Currently i just have it as this and thus taking care of it in the frontend:

score = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(6)])

But thats not great because i can put any value i want for example from the admin or any front end input i have. Sure i can do frontend validation to stop it from happening but django never let me down when it comes to their features so im sure theres something i can do

Upvotes: 1

Views: 419

Answers (1)

VJ Magar
VJ Magar

Reputation: 1052

You don't need to create additional field for score instead you can make score property of your model

class TradeBill(models.Model):
    ...
    @property
    def score(self):
           return self.first + self.second + self.third
    ...

EDIT Extending the answer to include a serializer. You can also include the property of the model in the serializer

class TradeBillSerializer(serializers.ModelSerializer):
       class Meta:
           fields = ("score", ...)

Also, you can use SerializerMethodField (as mentioned by @Saif eldeen Adel in the comments.

class TradeBillSerializer(serializers.ModelSerializer):
       
     score = serializers.SerializerMethodField()

     def get_score(self, obj):
         return obj.score

     class Meta:
           fields = ("score", ...)

SerializerMethodField provides the flexibility to perform adding processing or formatting to the field.

Upvotes: 2

Related Questions