How to use model variables in a view in Django

Asked

Viewed 752 times

0

I need to calculate the average of a school report where the data are filled in in Django Admin, I would like to take each value make the media and play on a table in View.

Code:

MODEL

class Cadastro_Boletim(models.Model):

    ra_aluno = models.ForeignKey(Aluno, models.DO_NOTHING, related_name='Nome')
    curso = models.ForeignKey(Curso, models.DO_NOTHING, db_column='Curso')   # Field name made lowercase.
    nome_disciplina = models.ForeignKey(Disciplina, models.DO_NOTHING, db_column='Nome_Discplina')
    MB1 = models.SmallIntegerField(blank=True, null=True)  # Field name made lowercase.
    SUB1 = models.SmallIntegerField(blank=True, null=True)
    MB2 = models.SmallIntegerField(blank=True, null=True)
    SUB2 = models.SmallIntegerField(blank=True, null=True)
    EX = models.SmallIntegerField(blank=True, null=True)
    regular = models.BooleanField("Ativo?",default=True)

VIEW

def boletim(request):    
    contexto = {
        'boletim': Cadastro_Boletim.objects.all()   
    }
    return render(request,"boletim.html", contexto)

That way it brings everything that has in the Model, but I can not do the average with the notes, could help me?

  • But the average between which fields?

  • Average between MB1 (1st quarter) and MB2 (2nd quarter)

1 answer

1


For the average between the bimonthes : MB1 and MB2 , you can do as follows:

from django.db import AVG, F 
Cadastro_Boletim.objects.aggregate(media_bimestres=AVG(F('MB1')*F('MB2')))

With this each element will have accessible a variable "media_bimesters" available for access.

  • Show ! Thanks Marlysson, just one more question, I can do this calculation by calling a function ?

  • @Gabrielgeorge I’m glad the answer came in handy. Could mark the answer as useful so that other people with the same problem solve it more easily.

  • @Gabrielgeorge Yes, you can. You want to pass a Registration Bulletin ( already filtered ) and return the average of that in specific? There are several forms for this, from a method in the model, to a "service".. what case? It would be good a new question for this. To keep the doubts isolated.

  • For example, I have my notes, and I wanted to call a function calcula_note, and play the values MB1 and MB2 in this function to be performed all the average calculation.

  • Do you have any modeling of this? Because it would be appropriate to have a Notabimonthly class associating a grade, the bimonthly and the student, with this being able to aggregate several bimonths to calculate the grade. The newsletter registration is responsible for what system concept?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.