Skip to content

Blog example: Quick and Sweet Django - Print queryset in a table format, for shell purposes #484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions config/django/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,8 @@
from config.settings.debug_toolbar.setup import DebugToolbarSetup # noqa

INSTALLED_APPS, MIDDLEWARE = DebugToolbarSetup.do_settings(INSTALLED_APPS, MIDDLEWARE)


SHELL_PLUS_IMPORTS = [
"from styleguide_example.blog_examples.print_qs_in_shell.utils import print_qs"
]
6 changes: 5 additions & 1 deletion mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,8 @@ ignore_missing_imports = True

[mypy-qrcode.*]
# Remove this when qrcode stubs are present
ignore_missing_imports = True
ignore_missing_imports = True

[mypy-tabulate.*]
# Remove this when qrcode stubs are present
ignore_missing_imports = True
1 change: 1 addition & 0 deletions requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ google-auth-oauthlib==1.2.1

pyotp==2.9.0
qrcode==8.0
tabulate==0.9.0
22 changes: 22 additions & 0 deletions styleguide_example/blog_examples/print_qs_in_shell/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from tabulate import tabulate


def tabulate_qs(queryset, *, fields: list[str] | None = None, exclude: list[str] | None = None) -> str:
# Make sure the table won't be empty
if not fields:
fields = [field.name for field in queryset.model._meta.fields]

if not exclude:
exclude = []

fields = [field for field in fields if field not in exclude]

return tabulate(
tabular_data=queryset.values_list(*fields),
headers=fields,
tablefmt="github",
)


def print_qs(queryset, *, fields: list[str] | None = None, exclude: list[str] | None = None) -> None:
print(tabulate_qs(queryset, fields=fields, exclude=exclude))
Loading