# How to use prefetch\_related to retrieve multiple rows similar to SQL

**URL:** <https://forum.djangoproject.com/t/how-to-use-prefetch-related-to-retrieve-multiple-rows-similar-to-sql/16082>\
**Category:** Using Django\
**Created:** [September 21, 2022, 7:01am UTC](https://forum.djangoproject.com/t/how-to-use-prefetch-related-to-retrieve-multiple-rows-similar-to-sql/16082 "2022-09-21T07:01:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![sohchienmin](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sohchienmin/32/10162_2.png) [@sohchienmin](https://forum.djangoproject.com/u/sohchienmin)\
**Post date:** [September 21, 2022, 7:01am UTC](https://forum.djangoproject.com/t/how-to-use-prefetch-related-to-retrieve-multiple-rows-similar-to-sql/16082/1 "2022-09-21T07:01:39Z")

</div>

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:

```auto
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:

```auto
| 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:

```auto
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:

```auto
| 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!
