I need to do the following sql query in django specifically in the views window, I need to filter the "Nota" according to which "Profesor" it belongs to
SQL QUERY
select *
from nota n join profesor on (profesor.id_asignatura = n.id_asignatura)
models.py
class Nota(models.Model):
id_nota = models.IntegerField(primary_key=True)
nota = models.IntegerField()
tipo_evaluacion = models.CharField(max_length=15)
fecha_evaluacion = models.DateField()
id_libro = models.ForeignKey(LibroClases, models.DO_NOTHING, db_column='id_libro')
id_asignatura = models.ForeignKey(Asignatura, models.DO_NOTHING, db_column='id_asignatura')
rut_alumno = models.ForeignKey(Alumno, models.DO_NOTHING, db_column='rut_alumno')
class Meta:
managed = True
db_table = 'nota'
class Profesor(models.Model):
rut_profesor = models.IntegerField(primary_key=True)
dv_profesor = models.CharField(max_length=1)
p_nombre = models.CharField(max_length=15)
s_nombre = models.CharField(max_length=15, blank=True, null=True)
ap_paterno = models.CharField(max_length=15)
ap_materno = models.CharField(max_length=15, blank=True, null=True)
especialidad = models.CharField(max_length=35)
fecha_contrato = models.DateField()
direccion = models.CharField(max_length=25)
id_colegio = models.ForeignKey(Colegio, models.DO_NOTHING, db_column='id_colegio', blank=True, null=True)
id_asignatura = models.ForeignKey(Asignatura, models.DO_NOTHING, db_column='id_asignatura')
id_comuna = models.ForeignKey(Comuna, models.DO_NOTHING, db_column='id_comuna')
class Meta:
managed = True
db_table = 'profesor'
Views.py
def vistaProfesor(request):
rut= request.user.rut_user
notas = Nota.objects.select_related??????????
CodePudding user response:
you can use loop for your data
for item in Nota.objects.all():
for items in Profesor.objects.all():
if item.id_asignatura == items.Profesor:
do something....
CodePudding user response:
To just get the notas with the corresponding id_asignatura you can use this filter.
def vistaProfesor(request):
rut= request.user.rut_user
notas = Nota.objects.filter(id_asignatura=rut.id_asignatura)
It might be useful to add a related_name/related_query_name to some ForeignKeys - depenmding on what you want to achieve.
https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey.related_query_name.related_name