File: list_model_info.py

package info (click to toggle)
python-django-extensions 4.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,812 kB
  • sloc: python: 18,601; javascript: 7,354; makefile: 108; xml: 17
file content (185 lines) | stat: -rw-r--r-- 6,532 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# -*- coding: utf-8 -*-
# Author: OmenApps. https://omenapps.com
import inspect

from django.apps import apps as django_apps
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import connection
from django_extensions.management.color import color_style
from django_extensions.management.utils import signalcommand

TAB = "        "
HALFTAB = "    "


class Command(BaseCommand):
    """A simple management command which lists model fields and methods."""

    help = "List out the fields and methods for each model"

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "--field-class",
            action="store_true",
            default=None,
            help="show class name of field.",
        )
        parser.add_argument(
            "--db-type",
            action="store_true",
            default=None,
            help="show database column type of field.",
        )
        parser.add_argument(
            "--signature",
            action="store_true",
            default=None,
            help="show the signature of method.",
        )
        parser.add_argument(
            "--all-methods",
            action="store_true",
            default=None,
            help="list all methods, including private and default.",
        )
        parser.add_argument(
            "--model",
            nargs="?",
            type=str,
            default=None,
            help="list the details for a single model. "
            "Input should be in the form appname.Modelname",
        )

    def list_model_info(self, options):
        style = color_style()
        INFO = getattr(style, "INFO", lambda x: x)
        WARN = getattr(style, "WARN", lambda x: x)
        BOLD = getattr(style, "BOLD", lambda x: x)

        FIELD_CLASS = (
            True
            if options.get("field_class", None) is not None
            else getattr(settings, "MODEL_INFO_FIELD_CLASS", False)
        )
        DB_TYPE = (
            True
            if options.get("db_type", None) is not None
            else getattr(settings, "MODEL_INFO_DB_TYPE", False)
        )
        SIGNATURE = (
            True
            if options.get("signature", None) is not None
            else getattr(settings, "MODEL_INFO_SIGNATURE", False)
        )
        ALL_METHODS = (
            True
            if options.get("all_methods", None) is not None
            else getattr(settings, "MODEL_INFO_ALL_METHODS", False)
        )
        MODEL = (
            options.get("model")
            if options.get("model", None) is not None
            else getattr(settings, "MODEL_INFO_MODEL", False)
        )

        default_methods = [
            "check",
            "clean",
            "clean_fields",
            "date_error_message",
            "delete",
            "from_db",
            "full_clean",
            "get_absolute_url",
            "get_deferred_fields",
            "prepare_database_save",
            "refresh_from_db",
            "save",
            "save_base",
            "serializable_value",
            "unique_error_message",
            "validate_unique",
        ]

        if MODEL:
            model_list = [django_apps.get_model(MODEL)]
        else:
            model_list = sorted(
                django_apps.get_models(),
                key=lambda x: (x._meta.app_label, x._meta.object_name),
                reverse=False,
            )
        for model in model_list:
            self.stdout.write(
                INFO(model._meta.app_label + "." + model._meta.object_name)
            )
            self.stdout.write(BOLD(HALFTAB + "Fields:"))

            for field in model._meta.get_fields():
                field_info = TAB + field.name + " -"

                if FIELD_CLASS:
                    try:
                        field_info += " " + field.__class__.__name__
                    except TypeError:
                        field_info += WARN(" TypeError (field_class)")
                    except AttributeError:
                        field_info += WARN(" AttributeError (field_class)")
                if FIELD_CLASS and DB_TYPE:
                    field_info += ","
                if DB_TYPE:
                    try:
                        field_info += " " + field.db_type(connection=connection)
                    except TypeError:
                        field_info += WARN(" TypeError (db_type)")
                    except AttributeError:
                        field_info += WARN(" AttributeError (db_type)")

                self.stdout.write(field_info)

            if ALL_METHODS:
                self.stdout.write(BOLD(HALFTAB + "Methods (all):"))
            else:
                self.stdout.write(BOLD(HALFTAB + "Methods (non-private/internal):"))

            for method_name in dir(model):
                try:
                    method = getattr(model, method_name)
                    if ALL_METHODS:
                        if callable(method) and not method_name[0].isupper():
                            if SIGNATURE:
                                signature = inspect.signature(method)
                            else:
                                signature = "()"
                            self.stdout.write(TAB + method_name + str(signature))
                    else:
                        if (
                            callable(method)
                            and not method_name.startswith("_")
                            and method_name not in default_methods
                            and not method_name[0].isupper()
                        ):
                            if SIGNATURE:
                                signature = inspect.signature(method)
                            else:
                                signature = "()"
                            self.stdout.write(TAB + method_name + str(signature))
                except AttributeError:
                    self.stdout.write(TAB + method_name + WARN(" - AttributeError"))
                except ValueError:
                    self.stdout.write(
                        TAB
                        + method_name
                        + WARN(" - ValueError (could not identify signature)")
                    )

            self.stdout.write("\n")

        self.stdout.write(INFO("Total Models Listed: %d" % len(model_list)))

    @signalcommand
    def handle(self, *args, **options):
        self.list_model_info(options)