MCPcopy
hub / github.com/django/django / rename_field

Method rename_field

django/db/migrations/state.py:307–371  ·  view source on GitHub ↗
(self, app_label, model_name, old_name, new_name)

Source from the content-addressed store, hash-verified

305 self.reload_model(*model_key, delay=delay)
306
307 def rename_field(self, app_label, model_name, old_name, new_name):
308 model_key = app_label, model_name
309 model_state = self.models[model_key]
310 # Rename the field.
311 fields = model_state.fields
312 try:
313 found = fields.pop(old_name)
314 except KeyError:
315 raise FieldDoesNotExist(
316 f"{app_label}.{model_name} has no field named '{old_name}'"
317 )
318 fields[new_name] = found
319 for field in fields.values():
320 # Fix from_fields to refer to the new field.
321 from_fields = getattr(field, "from_fields", None)
322 if from_fields:
323 field.from_fields = tuple(
324 [
325 new_name if from_field_name == old_name else from_field_name
326 for from_field_name in from_fields
327 ]
328 )
329 # Fix field names (e.g. for CompositePrimaryKey) to refer to the
330 # new field.
331 if field_names := getattr(field, "field_names", None):
332 if old_name in field_names:
333 field.field_names = tuple(
334 [
335 new_name if field_name == old_name else field_name
336 for field_name in field.field_names
337 ]
338 )
339 # Fix index/unique_together to refer to the new field.
340 options = model_state.options
341 for option in ("index_together", "unique_together"):
342 if option in options:
343 options[option] = {
344 tuple(new_name if n == old_name else n for n in together)
345 for together in options[option]
346 }
347 # Fix to_fields to refer to the new field.
348 delay = True
349 references = get_references(self, model_key, (old_name, found))
350 for *_, field, reference in references:
351 delay = False
352 if reference.to:
353 remote_field, to_fields = reference.to
354 if getattr(remote_field, "field_name", None) == old_name:
355 remote_field.field_name = new_name
356 if to_fields:
357 field.to_fields = tuple(
358 [
359 new_name if to_field_name == old_name else to_field_name
360 for to_field_name in to_fields
361 ]
362 )
363 if self._relations is not None:
364 old_name_lower = old_name.lower()

Calls 5

reload_modelMethod · 0.95
FieldDoesNotExistClass · 0.90
get_referencesFunction · 0.90
popMethod · 0.45
valuesMethod · 0.45