Таблица посещаемости на основе сеансов - с отдельными участниками в виде строк и сеансов в виде столбцов - PullRequest
0 голосов
/ 10 октября 2019

У меня есть таблица class_session с двумя столбцами.

+------------+----------+
| session_id | event_id |
+------------+----------+
|          1 |      159 |
|          2 |      159 |
|          3 |      160 |
|        ... |      ... |
+------------+----------+

А для event_id - 159 таблица class_attendance имеет четыре столбца следующим образом.

+---------------+------------+-----------------+------------+
| attendance_id | session_id | registration_id | attendance |
+---------------+------------+-----------------+------------+
|             1 |          1 |            2717 |          0 |
|             2 |          2 |            2717 |          1 |
|             3 |          1 |            2718 |          1 |
|             4 |          2 |            2718 |          0 |
+---------------+------------+-----------------+------------+

Iхотел бы создать таблицу HTML с строками - на основе количества DISTINCT registration_ids , связанного с событием (здесь, 2), и столбцов в зависимости от количества сеансов событие имеет.

Примерно так:

+-----------------+-----------+-----------+
| Registration ID | Session 1 | Session 2 |
+-----------------+-----------+-----------+
|            2717 |         0 |         1 |
|            2718 |         1 |         0 |
+-----------------+-----------+-----------+

Вот то, что я пробовал до сих пор.

attendance.py код:

...
if request.method == 'GET':
    event_id = 159
    db = get_db()

    # Get total number of sessions to create columns.
    cur_sessions = db.execute('SELECT COUNT(*) FROM class_session \
        WHERE event_id = ?', [event_id])
    no_of_sessions = cur_sessions.fetchone()[0]


    # Get DISTINCT registration_ids to track attendance against all sessions.
    cur_attendances = db.execute('SELECT DISTINCT class_attendance.attendance, \
        class_registration.registration_id \
        FROM class_attendance \
        INNER JOIN class_registration \
        ON class_registration.registration_id = class_attendance.registration_id \
        INNER JOIN class_session \
        ON class_session.session_id = class_attendance.session_id \
        WHERE class_session.event_id = ?', [event_id])

    attendance_list = get_sql_dict(cur_attendances, fetchone=False) # Returns sql rows with column names as dictionaries.

    return render_template('attendance.html', 
        attendance_list=attendance_list, no_of_sessions=no_of_sessions)
...

attendance.html код:

...
<table>
<thead>  
    <tr>
        <th>Registration ID</th>
        {% for i in range(no_of_sessions) %}
            <th>Session {{loop.index}}</th>
        {% endfor %}
    </tr>
</thead>
<tbody>
    {% for row in attendance_list %}
        <tr>
            <td>{{ row['registration_id'] }}</td>
            <!-- <td>I am stuck here</td> -->
        </tr>
    {% endfor %}
</tbody>
</table>
...
...