Convert RawQuerySet to QuerySet on DJango

0

I have the following Code:

from django.shortcuts import render
from estudiante.models import Estudiante
from caracterizacion.models import Tipo, Caracterizacion
from .filters import EstudianteFilter

# Create your views here.

def principal(request):
    query = '''SELECT DISTINCT ON (e.id) e.id, e.nombre, e.apellido, e.estado, e.documento, c.nivelado, s.nombre AS semestre, t.nombre AS tipo 
                FROM estudiante e 
                    JOIN caracterizacion c ON c.estudiante_id = e.id 
                    JOIN semestre s ON s.id=c.semestre_id 
                    JOIN tipo t ON t.id=c.tipo_id 
                    ORDER BY e.id, s.orden DESC'''
    estudiantes = Estudiante.objects.raw(query)

    estudiantes_filter = EstudianteFilter(request.GET, queryset=estudiantes)
    print(estudiantes_filter)


    contexto = {

        'estudiantes': estudiantes,
        'filter': estudiantes_filter,
    }
    return render(request, 'reporte/principal.html', contexto)

In the I have a query which I apply for the raw but when I try to use the raw in the django filter I get error 'RawQuerySet' object has no attribute 'all' this because django filter only accepts QuerySet, so I need to convert my RawQuerySet to a QuerySet.

I hope you can help me, thanks

    
asked by Cesar Martinez Quiroga 21.11.2018 в 07:44
source

1 answer

0

When you do a qs in Django, you can access related model fields using the double underscore, or __ . For example, if you have the model Estudiante related to Caracterización , I guess that through the field caracterizacion or similar, you can access the characterization fields using this notation, for example: caracterizacion__nivelado .

Of course, it will only take out the directly related ones, with which I would do a JOIN automagically .

Your query, if I understand it correctly, should be similar to this:

Estudiante.objects.all().values('nombre', 'apellido', 'estado', 'documento'..., 'caracterizacion__nivelado', 'caracterizacion__semestre__nombre', ...)
    
answered by 21.11.2018 / 11:32
source