generated at
sqlparse
sqlparseはSQLを分解して改行等フォーマットするのに便利

python
>>> sql = 'select * from foo where id in (select id from bar);' >>> print(sqlparse.format(sql, reindent=True)) SELECT * FROM foo WHERE id IN (SELECT id FROM bar);

Django ORMのSQLを読みやすく表示しながら試行錯誤したいとき
python
>>> print('\n'+sqlparse.format(str(User.objects.annotate(checkin=FilteredRelation('checkin', condition=Q(checkin__date='2021-10-01', checkin__location__isnull=False))).values('name', 'checkin__location').query), reindent=True)) SELECT "users"."name", checkin."location" FROM "users" LEFT OUTER JOIN "checkins" checkin ON ("users"."id" = checkin."user_id" AND ((checkin."date" = 2021-10-01 AND checkin."location" IS NOT NULL)))

オプションで出力を調整できる
しかし、雑誌向けに狭い幅で調整するような出力はないので、なかなか難しい
shimizukawa reindent reindent_aligned をよく使う

関数を定義しておくと再利用に便利
python
def printsql(query): from sqlparse import format as sfmt print(sfmt(str(query), reindent_aligned=True))