mardi 1 mars 2016

Nested SQL query in Django Views

So I searched and couldn't find any answer on this so far. I have a database where when I've put in:

SELECT event_name, team_number
FROM teams_by_event
WHERE team_number IN (SELECT team_number 
                    FROM teams_by_event 
                    WHERE event_name = '[user inputs event name]'
                    ) ORDER BY team_number;

It gives me exactly what I'm looking for in return. My problem is that I can't think of a way to do this in Django views, and what I've tried, just using the raw SQL in Django is not working either, I get a syntax error saying the last parenthesis on the SQL query is invalid.

views.py:

def teams_by_event(request, shorthand):
    code = TeamsByEvent.objects.filter(shorthand=shorthand)
    for event in TeamsByEvent.objects.raw('SELECT event_name, team_number \
                               FROM teams_by_event \
                               WHERE team_number IN \
                               (SELECT team_number \
                                FROM teams_by_event) \
                                WHERE shorthand= % s', [code])
    print (event.team_number, event.event_name)
    return render(request, 'event-info.html', {'info': info})

Aucun commentaire:

Enregistrer un commentaire