V
V
vladibuyanov2021-03-15 18:50:25
Django
vladibuyanov, 2021-03-15 18:50:25

How to do calculations in Django?

In the form ResultForm, I get the following data as input:

class ResultForm(ModelForm):
    class Meta:
        model = ResultInput
        fields = ['name', 'age', 'time', 'f1', 'f2', 'f3']
        widgets = {
            'name': TextInput(
                attrs={
                    'class': 'form-control',
                    'placeholder': "Enter your name"}
            ),
            'age': TextInput(
                attrs={
                    'class': 'form-control',
                    'placeholder': "Enter your age"}
            ),
            'time': TextInput(
                attrs={
                    'class': 'form-control',
                    'placeholder': "Enter time"}
            ),
            'f1': TextInput(
                attrs={
                    'class': 'form-control',
                    'placeholder': "Enter f1"}
            ),
            'f2': TextInput(
                attrs={
                    'class': 'form-control',
                    'placeholder': "Enter f2"}
            ),
            'f3': TextInput(
                attrs={
                    'class': 'form-control',
                    'placeholder': "Enter f2"}
            ),
        }


At the same time, in the model, I would like to have one more value that would correspond to the result of the calculations result = time * 100 / (f1 + f2 + f3) * 2. How can I make these calculations and write it as results in the same model?
I express my gratitude in advance to those who respond :)

Model:
class ResultInput(models.Model):
    name = models.CharField('Name', max_length=50)
    age = models.IntegerField('Age')
    time = models.IntegerField('Time')
    f1 = models.IntegerField('f1')
    f2 = models.IntegerField('f2')
    f3 = models.IntegerField('f3')
    result = models.IntegerField('result')

    def __str__(self):
        return self.name

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-03-15
@vladibuyanov

You can not write at all, or if you really need to, do it in save, well, keep in mind that it is unlikely that you will have exactly integer there.

class ResultInput(models.Model):
    name = models.CharField('Name', max_length=50)
    age = models.IntegerField('Age')
    time = models.IntegerField('Time')
    f1 = models.IntegerField('f1')
    f2 = models.IntegerField('f2')
    f3 = models.IntegerField('f3')

    def __str__(self):
        return self.name

    @property
    def result(self):
        return self.time * 100 / (self.f1 + self.f2 + self.f3) * 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question