Home > front end >  Django 3.2 how to add model decimal fields together inside model
Django 3.2 how to add model decimal fields together inside model

Time:01-01

I am trying to add all the decimalfields numbers together to form a sum inside the model

this is my model

class Ataskaita(models.Model):

    class Meta:
        verbose_name_plural = 'Ataskaitos'

    bendrija = models.ForeignKey(Bendrija, on_delete=models.CASCADE,
                                 related_name="ataskaita")

    atlyginimas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    sodra = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    vmi = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    pvm_saskaitos_kvitas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    bankines_operacijos = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    
    sum = models.DecimalField(max_digits=10, decimal_places=2)

and I want to add all the fields (atlyginimas, sodra, vmi, pvm_saskaitos_kvitas, bankines_operacijos) together so I have all of their total

I looked around stackoverflow and I think the only way to do it is to create a method, but I already tried it, and it wouldn't work as intended

CodePudding user response:

Django models are just python classes, so adding arbitrary methods like this should work fine:

class Ataskaita(models.Model):
    class Meta:
        verbose_name_plural = 'Ataskaitos'

    bendrija = models.ForeignKey(Bendrija, on_delete=models.CASCADE,
                                 related_name="ataskaita")

    atlyginimas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    sodra = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    vmi = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    pvm_saskaitos_kvitas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)
    bankines_operacijos = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0)

    @property
    def sum(self):
        return sum([self.atlyginimas, self.sodra, self.vmi, self.pvm_saskaitos_kvitas, self.bankines_operacijos])

You can instruct your serializers to display read-only properties with something like this:

class Ataskaita(serializers.ModelSerializer):
    sum = serializers.ReadOnlyField()

    class Meta:
        model = Ataskaita
        fields = '__all__'

Does that do what you wanted?

  • Related