Skip to content

Commit c8f1a7e

Browse files
authored
Merge pull request #484 from HackSoftware/blog/print-qs-in-shell
Blog example: Quick and Sweet Django - Print queryset in a table format, for shell purposes
2 parents f3ae4fc + 463c5ee commit c8f1a7e

File tree

4 files changed

+33
-1
lines changed

4 files changed

+33
-1
lines changed

config/django/base.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,3 +187,8 @@
187187
from config.settings.debug_toolbar.setup import DebugToolbarSetup # noqa
188188

189189
INSTALLED_APPS, MIDDLEWARE = DebugToolbarSetup.do_settings(INSTALLED_APPS, MIDDLEWARE)
190+
191+
192+
SHELL_PLUS_IMPORTS = [
193+
"from styleguide_example.blog_examples.print_qs_in_shell.utils import print_qs"
194+
]

mypy.ini

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,8 @@ ignore_missing_imports = True
4444

4545
[mypy-qrcode.*]
4646
# Remove this when qrcode stubs are present
47-
ignore_missing_imports = True
47+
ignore_missing_imports = True
48+
49+
[mypy-tabulate.*]
50+
# Remove this when qrcode stubs are present
51+
ignore_missing_imports = True

requirements/base.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ google-auth-oauthlib==1.2.1
3131

3232
pyotp==2.9.0
3333
qrcode==8.0
34+
tabulate==0.9.0
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from tabulate import tabulate
2+
3+
4+
def tabulate_qs(queryset, *, fields: list[str] | None = None, exclude: list[str] | None = None) -> str:
5+
# Make sure the table won't be empty
6+
if not fields:
7+
fields = [field.name for field in queryset.model._meta.fields]
8+
9+
if not exclude:
10+
exclude = []
11+
12+
fields = [field for field in fields if field not in exclude]
13+
14+
return tabulate(
15+
tabular_data=queryset.values_list(*fields),
16+
headers=fields,
17+
tablefmt="github",
18+
)
19+
20+
21+
def print_qs(queryset, *, fields: list[str] | None = None, exclude: list[str] | None = None) -> None:
22+
print(tabulate_qs(queryset, fields=fields, exclude=exclude))

0 commit comments

Comments
 (0)