Debian Codegraph @

src/polymorphic/showfields.py

raw
1 import re
2 from typing import TYPE_CHECKING, ClassVar
3
4 from django.db import models
5
6 if TYPE_CHECKING:
7 from polymorphic.models import PolymorphicModel
8
9 _Base = PolymorphicModel
10 else:
11 _Base = object
12
13 RE_DEFERRED: re.Pattern[str] = re.compile("_Deferred_.*")
14
15
16 class ShowFieldBase(_Base):
17 """base class for the ShowField... model mixins, does the work"""
18
19 # cause nicer multiline PolymorphicQuery output
20 polymorphic_query_multiline_output: ClassVar[bool] = True
21
22 polymorphic_showfield_type: ClassVar[bool] = False
23 polymorphic_showfield_content: ClassVar[bool] = False
24 polymorphic_showfield_deferred: ClassVar[bool] = False
25
26 # these may be overridden by the user
27 polymorphic_showfield_max_line_width: ClassVar[int | None] = None
28 polymorphic_showfield_max_field_width: ClassVar[int] = 20
29 polymorphic_showfield_old_format: ClassVar[bool] = False
30
31 def __repr__(self) -> str:
32 return self.__str__()
33
34 def _showfields_get_content(self, field_name: str, field_type: type = type(None)) -> str:
35 "helper for __unicode__"
36 content = getattr(self, field_name)
37 if self.polymorphic_showfield_old_format:
38 out = ": "
39 else:
40 out = " "
41 if issubclass(field_type, models.ForeignKey):
42 if content is None:
43 out += "None"
44 else:
45 out += content.__class__.__name__
46 elif issubclass(field_type, models.ManyToManyField):
47 out += f"{content.count()}"
48 elif isinstance(content, int):
49 out += str(content)
50 elif content is None:
51 out += "None"
52 else:
53 txt = str(content)
54 max_len = self.polymorphic_showfield_max_field_width
55 if len(txt) > max_len:
56 txt = f"{txt[: max_len - 2]}.."
57 out += f'"{txt}"'
58 return out
59
60 def _showfields_add_regular_fields(self, parts: list[tuple[bool, str, str]]) -> None:
61 "helper for __unicode__"
62 done_fields = set()
63 for field in self._meta.fields + self._meta.many_to_many:
64 if field.name in self.polymorphic_internal_model_fields or "_ptr" in field.name:
65 continue
66 if field.name in done_fields: # pragma: no cover
67 continue # work around django diamond inheritance problem
68 done_fields.add(field.name)
69
70 out = field.name
71
72 # if this is the standard primary key named "id", print it as we did with older versions of django_polymorphic
73 if field.primary_key and field.name == "id" and type(field) is models.AutoField:
74 out += f" {getattr(self, field.name)}"
75
76 # otherwise, display it just like all other fields (with correct type, shortened content etc.)
77 else:
78 if self.polymorphic_showfield_type:
79 out += f" ({type(field).__name__}"
80 if field.primary_key:
81 out += "/pk"
82 out += ")"
83
84 if self.polymorphic_showfield_content:
85 out += self._showfields_get_content(field.name, type(field))
86
87 parts.append((False, out, ","))
88
89 def _showfields_add_dynamic_fields(
90 self, field_list: list[str], title: str, parts: list[tuple[bool, str, str]]
91 ) -> None:
92 "helper for __unicode__"
93 parts.append((True, f"- {title}", ":"))
94 for field_name in field_list:
95 out = field_name
96 content = getattr(self, field_name)
97 if self.polymorphic_showfield_type:
98 out += f" ({type(content).__name__})"
99 if self.polymorphic_showfield_content:
100 out += self._showfields_get_content(field_name)
101
102 parts.append((False, out, ","))
103
104 def __str__(self) -> str:
105 # create list ("parts") containing one tuple for each title/field:
106 # ( bool: new section , item-text , separator to use after item )
107
108 # start with model name
109 parts = [(True, RE_DEFERRED.sub("", self.__class__.__name__), ":")]
110
111 # add all regular fields
112 self._showfields_add_regular_fields(parts)
113
114 # add annotate fields
115 annotate_names = getattr(self, "polymorphic_annotate_names", None)
116 if annotate_names is not None:
117 self._showfields_add_dynamic_fields(annotate_names, "Ann", parts)
118
119 # add extra() select fields
120 extra_select_names = getattr(self, "polymorphic_extra_select_names", None)
121 if extra_select_names is not None:
122 self._showfields_add_dynamic_fields(extra_select_names, "Extra", parts)
123
124 if self.polymorphic_showfield_deferred:
125 fields = self.get_deferred_fields()
126 if fields:
127 fields_str = ",".join(sorted(fields))
128 parts.append((False, f"deferred[{fields_str}]", ""))
129
130 # format result
131
132 indent = len(self.__class__.__name__) + 5
133 indentstr = "".rjust(indent)
134 out = ""
135 xpos = 0
136 possible_line_break_pos = None
137
138 for i in range(len(parts)):
139 new_section, p, separator = parts[i]
140 final = i == len(parts) - 1
141 if not final:
142 next_new_section, _, _ = parts[i + 1]
143
144 if (
145 self.polymorphic_showfield_max_line_width
146 and xpos + len(p) > self.polymorphic_showfield_max_line_width
147 and possible_line_break_pos is not None
148 ):
149 rest = out[possible_line_break_pos:]
150 out = out[:possible_line_break_pos]
151 out += f"\n{indentstr}{rest}"
152 xpos = indent + len(rest)
153
154 out += p
155 xpos += len(p)
156
157 if not final:
158 if not next_new_section:
159 out += separator
160 xpos += len(separator)
161 out += " "
162 xpos += 1
163
164 if not new_section:
165 possible_line_break_pos = len(out)
166
167 return f"<{out}>"
168
169
170 class ShowFieldType(ShowFieldBase):
171 """model mixin that shows the object's class and it's field types"""
172
173 polymorphic_showfield_type: ClassVar[bool] = True
174
175
176 class ShowFieldContent(ShowFieldBase):
177 """model mixin that shows the object's class, it's fields and field contents"""
178
179 polymorphic_showfield_content: ClassVar[bool] = True
180
181
182 class ShowFieldTypeAndContent(ShowFieldBase):
183 """model mixin, like ShowFieldContent, but also show field types"""
184
185 polymorphic_showfield_type: ClassVar[bool] = True
186 polymorphic_showfield_content: ClassVar[bool] = True