I have a User model and a SchoolHistory model.
User
| id | name |
SchoolHistory
| id | start_date | school_name | user_id |
A user can attend multiple school so for example this would be an example of a result from a SQL Query on the tables
Query:
SELECT
user.id,
school_history.start_date,
school_history.school_name
FROM user
JOIN school_history ON school_history.user_id = user.id
Query result:
| id | name | start_date | school_name |
| 1 | John | 1/1/2021 | Michigan |
| 1 | John | 1/1/2020 | Wisconsin |
Currently, I’m trying to replicate such a query using ORM. Based on my understanding, I’ll need to use prefetch_related since User has a reverse foreign key on SchoolHistory. So this is the ORM query that I’m using:
Query:
User.objects.prefetch_related(
Prefetch('school_history'), queryset=SchoolHistory.objects.order_by('start_date')
)
From my ModelSerializer based on User, the output I’m getting is:
| id | name | school_history |
| 1 | John | [{'start_date': '1/1/2021', 'school_name': 'Michigan'}, {'start_date': '1/1/2020', 'school_name': 'Wisconsin'}] |
How can I change my serializer to return multiple rows for each school similar to a SQL Query? Thanks!