Last active
February 9, 2022 13:26
-
-
Save tysonpaul89/828c53bb6eb9298553b83eba44da78aa to your computer and use it in GitHub Desktop.
Some Tips on Django ORM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Django ORM Tips: | |
| # When you have do an SQL"IN" operation, we generally do it like this. ie, convert the results to a list. | |
| # DON'T DO THIS | |
| seasons = list(Season.objects.values_list('name', flat=True)) | |
| result = Crops.objects.filter(season__name__in=seasons) | |
| print(result) | |
| # The above ORM query will generate the following SQL command: | |
| # SELECT * FROM crops c inner join season s on c.season_id = s.id where s.name in ('winter', 'summer', ...) | |
| # As you can see this will call the database 2 time. 1st when we ran the list() conversion and then on the print() operation. | |
| # INSTED USE THIS, BECAUSE ORM CONVERT THIS INTO A SUB-QUERY WHICH WILL DO THE SAME THING IN JUST ONE QUERY | |
| # SELECT * FROM crops c inner join season s on c.season_id = s.id where s.name in (SELECT name FROM season) | |
| seasons = Season.objects.values_list('name', flat=True) | |
| result = Crops.objects.filter(season__name__in=seasons) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment