django-extensions – display sql query in shell_plus

Small Django tip of the day. I use django-extensions as dev dependencies of all my project. Among the useful command, I use shell_plus which colorify my prompt and load all django models.

If you need to display SQL query in the shell, it is very easy :

  • You can set the variable SHELL_PLUS_PRINT_SQL = True in your settings.py file
  • Or you can just add the option --print-sql:
python manage.py shell_plus --print-sql

Django don’t query foreignKey if it’s not set

Using that option, I discored that Django is smarter than I though, it doesn’t query DB if the foreign_key is not set

>>> a.action_principale
>>> a.action_principale_id
>>> a.acteur_type_id
3

>>> a.acteur_type
SELECT "qfdmo_acteurtype"."id",
       "qfdmo_acteurtype"."code",
       "qfdmo_acteurtype"."libelle"
  FROM "qfdmo_acteurtype"
 WHERE "qfdmo_acteurtype"."id" = 3
 LIMIT 21

Execution time: 0.004706s [Database: default]
<ActeurType: artisan, commerce indépendant>

Here, action_principal_id is None, then Django doesn’t need to query DB to retrieve None foreign_key object action_principale

Leave a Reply

Your email address will not be published. Required fields are marked *