django-shellcraft 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-shellcraft
3
+ Version: 0.1.0
4
+ Summary: Rails-style console ergonomics for Django — pretty printing, model shortcuts, and schema inspection
5
+ Author-email: Siva <sivanandam03@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Siva
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ License-File: LICENSE
28
+ Keywords: console,developer-tools,django,orm,rails,shell
29
+ Classifier: Development Status :: 3 - Alpha
30
+ Classifier: Framework :: Django
31
+ Classifier: Framework :: Django :: 3.2
32
+ Classifier: Framework :: Django :: 4.0
33
+ Classifier: Framework :: Django :: 4.1
34
+ Classifier: Framework :: Django :: 4.2
35
+ Classifier: Framework :: Django :: 5.0
36
+ Classifier: Intended Audience :: Developers
37
+ Classifier: License :: OSI Approved :: MIT License
38
+ Classifier: Programming Language :: Python :: 3
39
+ Classifier: Programming Language :: Python :: 3.8
40
+ Classifier: Programming Language :: Python :: 3.9
41
+ Classifier: Programming Language :: Python :: 3.10
42
+ Classifier: Programming Language :: Python :: 3.11
43
+ Classifier: Programming Language :: Python :: 3.12
44
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
45
+ Requires-Python: >=3.8
46
+ Requires-Dist: django>=3.2
47
+ Provides-Extra: dev
48
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
49
+ Requires-Dist: pytest-django>=4.8; extra == 'dev'
50
+ Requires-Dist: pytest>=8.0; extra == 'dev'
51
+ Requires-Dist: ruff>=0.4; extra == 'dev'
52
+ Description-Content-Type: text/markdown
53
+
54
+ # django-shellcraft
55
+
56
+ Rails-style console ergonomics for Django — pretty printing, model shortcuts, and schema inspection.
57
+
58
+ Built for developers migrating from Ruby on Rails who miss the `rails console` experience.
59
+
60
+ ---
61
+
62
+ ## Installation
63
+
64
+ ```bash
65
+ pip install django-shellcraft
66
+ ```
67
+
68
+ Add to `INSTALLED_APPS`:
69
+
70
+ ```python
71
+ INSTALLED_APPS = [
72
+ ...
73
+ "shellcraft",
74
+ ]
75
+ ```
76
+
77
+ ## Usage
78
+
79
+ ```bash
80
+ python manage.py shellcraft
81
+ ```
82
+
83
+ All models are auto-imported into the shell namespace. IPython is used when available, falling back to the standard Python REPL.
84
+
85
+ > **Note:** shellcraft refuses to start when `DEBUG = False` as a production safety guard.
86
+
87
+ ---
88
+
89
+ ## Features
90
+
91
+ ### Model shortcuts
92
+
93
+ All shortcuts are injected as classmethods/instance methods at shell startup. Raw `User.objects.all()` is unchanged — pretty printing only happens through shellcraft methods.
94
+
95
+ | Method | Equivalent |
96
+ |---|---|
97
+ | `User.find(1)` | `User.objects.get(pk=1)` |
98
+ | `User.all()` | `User.objects.all()` + pretty print |
99
+ | `User.where(is_active=True)` | `User.objects.filter(...)` + pretty print |
100
+ | `User.first()` | `User.objects.first()` + pretty print |
101
+ | `User.last()` | `User.objects.last()` + pretty print |
102
+ | `User.count()` | `User.objects.count()` |
103
+ | `user.update(email="x@y.com")` | sets attrs + `save()` |
104
+ | `user.destroy()` | `user.delete()` |
105
+ | `User.fields()` | colored schema inspection |
106
+ | `tables()` | list all models across all apps |
107
+
108
+ ### Pretty printing
109
+
110
+ Single record:
111
+
112
+ ```
113
+ #<User:0x7f3a> {
114
+ :id => 1,
115
+ :username => "siva",
116
+ :email => "siva@example.com",
117
+ :is_active => true,
118
+ :created_at => 2024-01-15 10:30:00,
119
+ }
120
+ ```
121
+
122
+ Multiple records:
123
+
124
+ ```
125
+ [
126
+ [0] #<User:0x7f3a> {
127
+ :id => 1,
128
+ :username => "siva",
129
+ },
130
+ [1] #<User:0x7f3b> {
131
+ :id => 2,
132
+ :username => "kumar",
133
+ }
134
+ ]
135
+ 2 records
136
+ ```
137
+
138
+ Color mapping:
139
+
140
+ | Type | Color |
141
+ |---|---|
142
+ | `int`, `float` | blue |
143
+ | `str` | yellow |
144
+ | `True` | green |
145
+ | `False`, `None` | red |
146
+ | `datetime`, `date` | cyan |
147
+ | field types | cyan |
148
+ | record index `[0]` | gray |
149
+
150
+ ### Schema inspection
151
+
152
+ ```python
153
+ User.fields()
154
+ ```
155
+
156
+ ```
157
+ User {
158
+ :id AutoField
159
+ :username CharField
160
+ :email CharField
161
+ :is_active BooleanField
162
+ :created_at DateTimeField
163
+ :group_id ForeignKey null: true
164
+ }
165
+ ```
166
+
167
+ ### List all tables
168
+
169
+ ```python
170
+ tables()
171
+ ```
172
+
173
+ ```
174
+ auth.User
175
+ auth.Group
176
+ auth.Permission
177
+ myapp.Post
178
+ myapp.Comment
179
+
180
+ 5 tables
181
+ ```
182
+
183
+ ### Manual pretty printing
184
+
185
+ `ap()` is available directly for any model instance or queryset:
186
+
187
+ ```python
188
+ ap(User.objects.filter(is_staff=True))
189
+ ```
190
+
191
+ ---
192
+
193
+ ## Requirements
194
+
195
+ - Python 3.8+
196
+ - Django 3.2, 4.0, 4.1, 4.2, or 5.0
197
+ - django-extensions >= 3.0
198
+
199
+ Optional: `ipython` for an enhanced shell experience.
200
+
201
+ ---
202
+
203
+ ## Development
204
+
205
+ ```bash
206
+ git clone https://github.com/yourusername/django-shellcraft
207
+ cd django-shellcraft
208
+ pip install -e ".[dev]"
209
+ pytest
210
+ ```
211
+
212
+ ---
213
+
214
+ ## License
215
+
216
+ MIT
@@ -0,0 +1,10 @@
1
+ shellcraft/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ shellcraft/mixins.py,sha256=h8OfST2Y01UwBtr8zT58PC9r0dARUvZeKK775h3qokY,4477
3
+ shellcraft/printer.py,sha256=IJnPFpfJ1tQgtf-5I51FR4kbAVWAIud68fQREyfw6wc,7255
4
+ shellcraft/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ shellcraft/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ shellcraft/management/commands/shellcraft.py,sha256=UGItbw7fy2tfPric0D-VRZcNPafKcm82ET2GLlCTaUI,3535
7
+ django_shellcraft-0.1.0.dist-info/METADATA,sha256=7OAA-4YLHy82VgZXEzb9n-djqRwRGMr2gpeqkClvQQg,5517
8
+ django_shellcraft-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
9
+ django_shellcraft-0.1.0.dist-info/licenses/LICENSE,sha256=F24jcS4eawjwevYk9Q8FL_pYRDzLHV5whzfN1n9DNJA,1061
10
+ django_shellcraft-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Siva
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
shellcraft/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
File without changes
@@ -0,0 +1,95 @@
1
+ import warnings
2
+
3
+ from django.conf import settings
4
+ from django.core.management.base import BaseCommand, CommandError
5
+
6
+ BANNER = """\
7
+ shellcraft {version} — Rails-style Django shell
8
+ User.find(1) User.all() User.where(active=True)
9
+ User.first() User.last() User.count()
10
+ user.update(k=v) user.destroy()
11
+ User.fields() tables()
12
+ """
13
+
14
+
15
+ class Command(BaseCommand):
16
+ help = "Rails-style Django shell with pretty printing and model shortcuts"
17
+
18
+ def handle(self, *_args, **_options):
19
+ # Use CommandError instead of SystemExit so Django's management
20
+ # framework can format the message via stderr and return a proper
21
+ # non-zero exit code. SystemExit would skip that pipeline entirely.
22
+ if not settings.DEBUG:
23
+ raise CommandError(
24
+ "shellcraft: refusing to run with DEBUG=False (production guard)"
25
+ )
26
+
27
+ from shellcraft.mixins import inject
28
+
29
+ inject()
30
+
31
+ namespace = self._build_namespace()
32
+ self._start_shell(namespace)
33
+
34
+ def _build_namespace(self):
35
+ from django.apps import apps
36
+
37
+ from shellcraft.printer import CYAN, RESET, ap
38
+
39
+ def tables():
40
+ all_models = apps.get_models()
41
+ for model in all_models:
42
+ label = model._meta.app_label
43
+ self.stdout.write(f" {CYAN}{label}{RESET}.{model.__name__}")
44
+ self.stdout.write(f"\n{len(all_models)} tables")
45
+
46
+ namespace = {
47
+ "ap": ap,
48
+ "tables": tables,
49
+ }
50
+
51
+ # Build model-name → model mapping, warning when two apps define a
52
+ # model with the same class name. Without the warning the second
53
+ # model silently shadows the first, which is a confusing footgun when
54
+ # working with multi-app projects (e.g. two apps both define `Profile`).
55
+ seen: dict = {}
56
+ for model in apps.get_models():
57
+ name = model.__name__
58
+ if name in seen:
59
+ warnings.warn(
60
+ f"shellcraft: model name conflict — '{name}' exists in both "
61
+ f"'{seen[name]._meta.app_label}' and '{model._meta.app_label}'. "
62
+ f"The '{model._meta.app_label}.{name}' version is used in the "
63
+ "shell namespace. Access the other via "
64
+ "apps.get_model('<app_label>', '<ModelName>').",
65
+ stacklevel=2,
66
+ )
67
+ seen[name] = model
68
+ namespace[name] = model
69
+
70
+ return namespace
71
+
72
+ def _start_shell(self, namespace):
73
+ from shellcraft import __version__
74
+
75
+ banner = BANNER.format(version=__version__)
76
+ self.stdout.write(banner)
77
+
78
+ # Detect which shell is available before entering it, so that
79
+ # code.interact is never called inside an `except` block. If it were,
80
+ # Python would set __context__ on every shell exception to the
81
+ # ModuleNotFoundError, producing spurious "During handling of the above
82
+ # exception" noise on every traceback the user sees.
83
+ use_ipython = False
84
+ try:
85
+ import IPython # noqa: F401
86
+ use_ipython = True
87
+ except ImportError:
88
+ self.stdout.write("(IPython not found — using standard Python shell)\n")
89
+
90
+ if use_ipython:
91
+ import IPython
92
+ IPython.start_ipython(argv=["--no-banner"], user_ns=namespace)
93
+ else:
94
+ import code
95
+ code.interact(banner="", local=namespace)
shellcraft/mixins.py ADDED
@@ -0,0 +1,138 @@
1
+ import warnings
2
+
3
+ _INJECTED = False
4
+
5
+
6
+ def inject():
7
+ """Inject Rails-style class/instance methods onto Django's base Model.
8
+
9
+ Safe to call multiple times — idempotent after first call.
10
+ Only call this from the shellcraft management command.
11
+
12
+ Raises RuntimeError when DEBUG is False so that an accidental import of
13
+ this module in a production Celery worker or WSGI request cannot
14
+ activate the shell shortcuts on every model in the process.
15
+ """
16
+ global _INJECTED
17
+ if _INJECTED:
18
+ return
19
+
20
+ # Belt-and-suspenders production guard. The management command also
21
+ # checks DEBUG before calling inject(), but inject() is a public function
22
+ # and could be called from user code (e.g. a custom management command
23
+ # that wraps shellcraft). Checking here ensures the guard can never be
24
+ # bypassed simply by calling inject() directly.
25
+ from django.conf import settings
26
+ if not settings.DEBUG:
27
+ raise RuntimeError(
28
+ "shellcraft.inject() must not be called when DEBUG=False. "
29
+ "The shellcraft shell is a development-only tool."
30
+ )
31
+
32
+ _INJECTED = True
33
+
34
+ from django.db import models
35
+
36
+ from shellcraft.printer import ap, format_fields
37
+
38
+ def _find(cls, pk):
39
+ return cls.objects.get(pk=pk)
40
+
41
+ def _all(cls):
42
+ # Return the queryset so callers can assign: `users = User.all()`.
43
+ # Printing and returning are both useful; returning None was a silent
44
+ # footgun for anyone who stored the result.
45
+ qs = cls.objects.all()
46
+ ap(qs)
47
+ return qs
48
+
49
+ def _where(cls, **kwargs):
50
+ qs = cls.objects.filter(**kwargs)
51
+ ap(qs)
52
+ return qs
53
+
54
+ def _first(cls):
55
+ obj = cls.objects.first()
56
+ if obj is not None:
57
+ ap(obj)
58
+ return obj
59
+
60
+ def _last(cls):
61
+ obj = cls.objects.last()
62
+ if obj is not None:
63
+ ap(obj)
64
+ return obj
65
+
66
+ def _count(cls):
67
+ return cls.objects.count()
68
+
69
+ def _fields(cls):
70
+ print(format_fields(cls))
71
+
72
+ def _update(self, **kwargs):
73
+ # Block dunder and private-attribute keys outright. Allowing
74
+ # user.update(__class__=X) or user.update(__dict__={...}) would let
75
+ # shell users overwrite Python internals, bypassing Django's field
76
+ # validation entirely and corrupting the object in memory.
77
+ for key in kwargs:
78
+ if key.startswith("_"):
79
+ raise ValueError(
80
+ f"shellcraft: cannot update private or dunder attribute '{key}'. "
81
+ "Pass only model field names."
82
+ )
83
+
84
+ # Warn (don't raise) for keys that don't correspond to any known field
85
+ # on this model. Django's save() will silently ignore them, which is
86
+ # confusing during interactive development.
87
+ valid_fields = {f.attname for f in self.__class__._meta.concrete_fields}
88
+ valid_fields.update(f.name for f in self.__class__._meta.concrete_fields)
89
+ valid_fields.update(f.name for f in self.__class__._meta.many_to_many)
90
+
91
+ for key in kwargs:
92
+ if key not in valid_fields:
93
+ warnings.warn(
94
+ f"shellcraft: '{key}' is not a recognised field on "
95
+ f"{self.__class__.__name__} — the attribute will be set "
96
+ "but will not be persisted by Django's save().",
97
+ stacklevel=2,
98
+ )
99
+
100
+ for key, value in kwargs.items():
101
+ setattr(self, key, value)
102
+ self.save()
103
+ return self
104
+
105
+ def _destroy(self):
106
+ return self.delete()
107
+
108
+ class_methods = {
109
+ 'find': _find,
110
+ 'all': _all,
111
+ 'where': _where,
112
+ 'first': _first,
113
+ 'last': _last,
114
+ 'count': _count,
115
+ 'fields': _fields,
116
+ }
117
+ instance_methods = {
118
+ 'update': _update,
119
+ 'destroy': _destroy,
120
+ }
121
+
122
+ for name, fn in class_methods.items():
123
+ _safe_inject(models.Model, name, classmethod(fn))
124
+
125
+ for name, fn in instance_methods.items():
126
+ _safe_inject(models.Model, name, fn)
127
+
128
+
129
+ def _safe_inject(cls, name, method):
130
+ if hasattr(cls, name):
131
+ existing = getattr(cls, name)
132
+ warnings.warn(
133
+ f"shellcraft: '{name}' already exists on {cls.__name__} "
134
+ f"(defined in {getattr(existing, '__module__', '?')}) — skipping injection",
135
+ stacklevel=3,
136
+ )
137
+ return
138
+ setattr(cls, name, method)
shellcraft/printer.py ADDED
@@ -0,0 +1,200 @@
1
+ import datetime
2
+ import re
3
+ from decimal import Decimal
4
+
5
+ # ANSI color codes
6
+ BLUE = '\033[34m'
7
+ YELLOW = '\033[33m'
8
+ GREEN = '\033[32m'
9
+ RED = '\033[31m'
10
+ CYAN = '\033[36m'
11
+ GRAY = '\033[90m'
12
+ RESET = '\033[0m'
13
+
14
+ _FIELD_TYPE_COLORS = {
15
+ 'AutoField': CYAN, 'BigAutoField': CYAN, 'SmallAutoField': CYAN,
16
+ 'IntegerField': BLUE, 'BigIntegerField': BLUE, 'SmallIntegerField': BLUE,
17
+ 'FloatField': BLUE, 'DecimalField': BLUE,
18
+ 'CharField': YELLOW, 'TextField': YELLOW, 'SlugField': YELLOW,
19
+ 'EmailField': YELLOW, 'URLField': YELLOW,
20
+ 'BooleanField': GREEN, 'NullBooleanField': GREEN,
21
+ 'DateField': CYAN, 'DateTimeField': CYAN, 'TimeField': CYAN,
22
+ 'ForeignKey': GRAY, 'OneToOneField': GRAY, 'ManyToManyField': GRAY,
23
+ }
24
+
25
+ # Matches any ANSI CSI escape sequence — covers colors, cursor movement,
26
+ # clear-screen codes, etc. Used to sanitize user-supplied string values
27
+ # before they reach the terminal to prevent terminal injection.
28
+ _ANSI_ESCAPE_RE = re.compile(r'\x1b\[[0-9;]*[A-Za-z]')
29
+
30
+
31
+ def _strip_ansi(s: str) -> str:
32
+ """Remove ANSI escape sequences embedded in a user-supplied string value.
33
+
34
+ A database value such as ``"\\033[2J\\033[0;0H"`` would otherwise clear the
35
+ terminal when printed. We strip rather than escape because the point is
36
+ display-only output; the raw data is unmodified in the database.
37
+ """
38
+ return _ANSI_ESCAPE_RE.sub('', s)
39
+
40
+
41
+ def colorize(value):
42
+ """Return ANSI-colored string representation of a Python value."""
43
+ # bool must be checked before int because bool is a subclass of int.
44
+ if isinstance(value, bool):
45
+ return f"{GREEN}true{RESET}" if value else f"{RED}false{RESET}"
46
+ if isinstance(value, (int, float, Decimal)):
47
+ return f"{BLUE}{value}{RESET}"
48
+ if isinstance(value, str):
49
+ # Sanitize before wrapping in color codes so embedded escape sequences
50
+ # cannot bleed into the terminal (terminal injection prevention).
51
+ return f'{YELLOW}"{_strip_ansi(value)}"{RESET}'
52
+ if value is None:
53
+ return f"{RED}nil{RESET}"
54
+ # datetime.datetime is a subclass of datetime.date, so both are matched
55
+ # here. datetime.time is a separate type and also colored cyan to match
56
+ # the field-type color for TimeField.
57
+ if isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
58
+ return f"{CYAN}{value}{RESET}"
59
+ return str(value)
60
+
61
+
62
+ def _get_fields(obj):
63
+ """Return list of (attname, value) for concrete fields of a model instance."""
64
+ return [
65
+ (field.attname, getattr(obj, field.attname, None))
66
+ for field in obj.__class__._meta.concrete_fields
67
+ ]
68
+
69
+
70
+ def _format_record(obj):
71
+ """Format a single model instance as an awesome_print-style string."""
72
+ cls = obj.__class__
73
+ header = f"#<{cls.__name__}:{hex(id(obj))}>"
74
+ fields = _get_fields(obj)
75
+
76
+ max_key_len = max((len(name) for name, _ in fields), default=0)
77
+
78
+ lines = [f"{header} {{"]
79
+ for name, value in fields:
80
+ key = f":{name}".ljust(max_key_len + 1)
81
+ lines.append(f" {key} => {colorize(value)},")
82
+ lines.append("}")
83
+ return '\n'.join(lines)
84
+
85
+
86
+ def _is_queryset_like(obj) -> bool:
87
+ """Return True if *obj* is a Django QuerySet or a compatible iterable.
88
+
89
+ Design:
90
+ - We prefer a concrete ``isinstance`` check when Django is importable so
91
+ that objects such as ``ModelForm`` (which has both ``.__iter__`` and
92
+ ``.model``) are not mistakenly treated as querysets.
93
+ - A duck-typing fallback is kept so that lightweight test mocks (which
94
+ carry ``__iter__`` and ``.model`` but are not real QuerySet instances)
95
+ continue to work without requiring a live Django setup in every test.
96
+ - The ``not hasattr(obj, '_meta')`` guard prevents a single model
97
+ instance from being routed into the list path if it ever exposes
98
+ ``.model`` (uncommon, but possible with custom model mixins).
99
+ """
100
+ try:
101
+ from django.db.models.query import QuerySet
102
+ if isinstance(obj, QuerySet):
103
+ return True
104
+ except ImportError:
105
+ pass
106
+
107
+ # Duck-typing fallback for test mocks and custom queryset-like objects.
108
+ return (
109
+ hasattr(obj, '__iter__')
110
+ and hasattr(obj, 'model')
111
+ and not hasattr(obj, '_meta')
112
+ )
113
+
114
+
115
+ def ap(obj):
116
+ """Pretty-print a model instance or queryset in awesome_print style."""
117
+ if obj is None:
118
+ print(colorize(None))
119
+ return
120
+
121
+ if _is_queryset_like(obj):
122
+ _print_queryset(list(obj))
123
+ return
124
+
125
+ # Single model instance
126
+ if hasattr(obj, '_meta'):
127
+ print(_format_record(obj))
128
+ return
129
+
130
+ print(repr(obj))
131
+
132
+
133
+ def _print_queryset(records):
134
+ if not records:
135
+ print("[]")
136
+ return
137
+
138
+ if len(records) == 1:
139
+ print(_format_record(records[0]))
140
+ return
141
+
142
+ # Precompute the width of the widest index label (e.g. "[99]" = 4 chars)
143
+ # so that all headers and field lines stay aligned for any result count.
144
+ max_idx_width = len(f"[{len(records) - 1}]")
145
+ # Prefix for the record header line: " [N…] "
146
+ content_start = 4 + max_idx_width + 1
147
+ # Field lines are indented 4 more chars than the header start (inside {}).
148
+ field_indent = " " * (content_start + 4)
149
+ close_indent = " " * content_start
150
+
151
+ print("[")
152
+ for i, record in enumerate(records):
153
+ is_last = i == len(records) - 1
154
+ fields = _get_fields(record)
155
+ cls = record.__class__
156
+ header = f"#<{cls.__name__}:{hex(id(record))}>"
157
+ max_key_len = max((len(name) for name, _ in fields), default=0)
158
+
159
+ # Pad the plain label before applying color so ljust counts visible
160
+ # characters only (ANSI codes are zero-width).
161
+ idx_label = f"[{i}]".ljust(max_idx_width)
162
+ idx_colored = f"{GRAY}{idx_label}{RESET}"
163
+
164
+ print(f" {idx_colored} {header} {{")
165
+ for name, value in fields:
166
+ key = f":{name}".ljust(max_key_len + 1)
167
+ print(f"{field_indent}{key} => {colorize(value)},")
168
+ comma = "" if is_last else ","
169
+ print(f"{close_indent}}}{comma}")
170
+ print("]")
171
+ count = len(records)
172
+ print(f"{count} records") # count is always >= 2 here; single records exit early above
173
+
174
+
175
+ def format_fields(model_class):
176
+ """Return a colored schema summary for a model class."""
177
+ concrete = list(model_class._meta.concrete_fields)
178
+ m2m = list(model_class._meta.many_to_many)
179
+
180
+ all_names = [f.attname for f in concrete] + [f.name for f in m2m]
181
+ max_name_len = max((len(n) for n in all_names), default=0)
182
+
183
+ lines = [f"{CYAN}{model_class.__name__}{RESET} {{"]
184
+
185
+ for field in concrete:
186
+ type_name = field.__class__.__name__
187
+ color = _FIELD_TYPE_COLORS.get(type_name, RESET)
188
+ name = f":{field.attname}".ljust(max_name_len + 1)
189
+ nullable = getattr(field, 'null', False)
190
+ null_tag = f" {GRAY}null: true{RESET}" if nullable else ""
191
+ lines.append(f" {name} {color}{type_name}{RESET}{null_tag}")
192
+
193
+ for field in m2m:
194
+ type_name = field.__class__.__name__
195
+ color = _FIELD_TYPE_COLORS.get(type_name, GRAY)
196
+ name = f":{field.name}".ljust(max_name_len + 1)
197
+ lines.append(f" {name} {color}{type_name}{RESET}")
198
+
199
+ lines.append("}")
200
+ return '\n'.join(lines)