Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Building a Markdown summary of Django group permissions#
Django SQL Dashboard can display rendered markdown generated by a SQL query.
Here’s a query I figured out today for showing a summary of all Django groups, their members and the list of permissions those groups hold:
1select2 (3 '# ' || (4 select5 name6 from7 auth_group8 where9 id = auth_group_original.id10 ) || '11
12' || (13 select14 count(*)15 from16 auth_user_groups17 where18 auth_user_groups.group_id = auth_group_original.id19 ) || ' members:20
21' || (22 select23 string_agg(auth_user.username, ', ')24 from25 auth_user26 join auth_user_groups on auth_user_groups.user_id = auth_user.id27 where28 auth_user_groups.group_id = auth_group_original.id29 ) || '30
31Permissions:32
33' || (34 select35 coalesce(36 string_agg(37 '* ' || auth_permission.name,38 '39'40 ),41 'No permissions'42 )43 from44 auth_permission45 join auth_group_permissions on auth_group_permissions.permission_id = auth_permission.id46 where47 auth_group_permissions.group_id = auth_group_original.id48 )49 ) as markdown50from51 auth_group auth_group_originalThe output looks like this:

The first time I ran this I got back null for the Markdown for one of the records - it turned out that one of my groups had no permissions at all, so this query:
1select2 string_agg(3 '* ' || auth_permission.name,4 '5'6 )7from8 auth_permission9 join auth_group_permissions on auth_group_permissions.permission_id = auth_permission.id10where11 auth_group_permissions.group_id = auth_group_original.idReturned null - and concatenating null to everything else produced null too.
The fix was to add a coalesce() - which returns the first not-null argument - like this:
1select coalesce(string_agg(...), 'No permissions')