MCPcopy
hub / github.com/tortoise/tortoise-orm / _init_relations

Method _init_relations

tortoise/apps.py:126–305  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

124 )
125
126 def _init_relations(self) -> None:
127 def get_related_model(related_app_name: str, related_model_name: str) -> type[Model]:
128 """
129 Test, if app and model really exist. Throws a ConfigurationError with a hopefully
130 helpful message. If successful, returns the requested model.
131
132 :raises ConfigurationError: If no such app exists.
133 """
134 try:
135 return self.apps[related_app_name][related_model_name]
136 except KeyError:
137 if related_app_name not in self.apps:
138 raise ConfigurationError(
139 f"No app with name '{related_app_name}' registered."
140 f" Please check your model names in ForeignKeyFields"
141 f" and configurations."
142 )
143 raise ConfigurationError(
144 f"No model with name '{related_model_name}' registered in"
145 f" app '{related_app_name}'."
146 )
147
148 def split_reference(reference: str) -> tuple[str, str]:
149 """
150 Validate, if reference follow the official naming conventions. Throws a
151 ConfigurationError with a hopefully helpful message. If successful,
152 returns the app and the model name.
153
154 :raises ConfigurationError: If reference is invalid.
155 """
156 if len(items := reference.split(".")) != 2: # pragma: nocoverage
157 raise ConfigurationError(
158 f"'{reference}' is not a valid model reference Bad Reference."
159 " Should be something like '<appname>.<modelname>'."
160 )
161 return items[0], items[1]
162
163 def init_fk_o2o_field(model: type[Model], field: str, is_o2o: bool = False) -> None:
164 fk_object = cast(
165 "OneToOneFieldInstance | ForeignKeyFieldInstance", model._meta.fields_map[field]
166 )
167 reference = fk_object.model_name
168 if not isinstance(reference, str):
169 related_model: type[Model] = reference
170 related_model_name = related_model.__name__
171 else:
172 related_app_name, related_model_name = split_reference(reference)
173 related_model = get_related_model(related_app_name, related_model_name)
174
175 if to_field := fk_object.to_field:
176 related_field = related_model._meta.fields_map.get(to_field)
177 if not related_field:
178 raise ConfigurationError(
179 f'there is no field named "{to_field}" in model "{related_model_name}"'
180 )
181 if not related_field.unique:
182 raise ConfigurationError(
183 f'field "{to_field}" in model "{related_model_name}" is not unique'

Callers 2

init_appMethod · 0.95
_load_from_configMethod · 0.95

Calls 6

ConfigurationErrorClass · 0.90
get_m2m_filtersFunction · 0.90
itemsMethod · 0.80
updateMethod · 0.80
add_fieldMethod · 0.45

Tested by

no test coverage detected