Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

state.py 40KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. import copy
  2. from collections import defaultdict
  3. from contextlib import contextmanager
  4. from functools import partial
  5. from django.apps import AppConfig
  6. from django.apps.registry import Apps
  7. from django.apps.registry import apps as global_apps
  8. from django.conf import settings
  9. from django.core.exceptions import FieldDoesNotExist
  10. from django.db import models
  11. from django.db.migrations.utils import field_is_referenced, get_references
  12. from django.db.models import NOT_PROVIDED
  13. from django.db.models.fields.related import RECURSIVE_RELATIONSHIP_CONSTANT
  14. from django.db.models.options import DEFAULT_NAMES, normalize_together
  15. from django.db.models.utils import make_model_tuple
  16. from django.utils.functional import cached_property
  17. from django.utils.module_loading import import_string
  18. from django.utils.version import get_docs_version
  19. from .exceptions import InvalidBasesError
  20. from .utils import resolve_relation
  21. def _get_app_label_and_model_name(model, app_label=""):
  22. if isinstance(model, str):
  23. split = model.split(".", 1)
  24. return tuple(split) if len(split) == 2 else (app_label, split[0])
  25. else:
  26. return model._meta.app_label, model._meta.model_name
  27. def _get_related_models(m):
  28. """Return all models that have a direct relationship to the given model."""
  29. related_models = [
  30. subclass
  31. for subclass in m.__subclasses__()
  32. if issubclass(subclass, models.Model)
  33. ]
  34. related_fields_models = set()
  35. for f in m._meta.get_fields(include_parents=True, include_hidden=True):
  36. if (
  37. f.is_relation
  38. and f.related_model is not None
  39. and not isinstance(f.related_model, str)
  40. ):
  41. related_fields_models.add(f.model)
  42. related_models.append(f.related_model)
  43. # Reverse accessors of foreign keys to proxy models are attached to their
  44. # concrete proxied model.
  45. opts = m._meta
  46. if opts.proxy and m in related_fields_models:
  47. related_models.append(opts.concrete_model)
  48. return related_models
  49. def get_related_models_tuples(model):
  50. """
  51. Return a list of typical (app_label, model_name) tuples for all related
  52. models for the given model.
  53. """
  54. return {
  55. (rel_mod._meta.app_label, rel_mod._meta.model_name)
  56. for rel_mod in _get_related_models(model)
  57. }
  58. def get_related_models_recursive(model):
  59. """
  60. Return all models that have a direct or indirect relationship
  61. to the given model.
  62. Relationships are either defined by explicit relational fields, like
  63. ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another
  64. model (a superclass is related to its subclasses, but not vice versa). Note,
  65. however, that a model inheriting from a concrete model is also related to
  66. its superclass through the implicit *_ptr OneToOneField on the subclass.
  67. """
  68. seen = set()
  69. queue = _get_related_models(model)
  70. for rel_mod in queue:
  71. rel_app_label, rel_model_name = (
  72. rel_mod._meta.app_label,
  73. rel_mod._meta.model_name,
  74. )
  75. if (rel_app_label, rel_model_name) in seen:
  76. continue
  77. seen.add((rel_app_label, rel_model_name))
  78. queue.extend(_get_related_models(rel_mod))
  79. return seen - {(model._meta.app_label, model._meta.model_name)}
  80. class ProjectState:
  81. """
  82. Represent the entire project's overall state. This is the item that is
  83. passed around - do it here rather than at the app level so that cross-app
  84. FKs/etc. resolve properly.
  85. """
  86. def __init__(self, models=None, real_apps=None):
  87. self.models = models or {}
  88. # Apps to include from main registry, usually unmigrated ones
  89. if real_apps is None:
  90. real_apps = set()
  91. else:
  92. assert isinstance(real_apps, set)
  93. self.real_apps = real_apps
  94. self.is_delayed = False
  95. # {remote_model_key: {model_key: {field_name: field}}}
  96. self._relations = None
  97. @property
  98. def relations(self):
  99. if self._relations is None:
  100. self.resolve_fields_and_relations()
  101. return self._relations
  102. def add_model(self, model_state):
  103. model_key = model_state.app_label, model_state.name_lower
  104. self.models[model_key] = model_state
  105. if self._relations is not None:
  106. self.resolve_model_relations(model_key)
  107. if "apps" in self.__dict__: # hasattr would cache the property
  108. self.reload_model(*model_key)
  109. def remove_model(self, app_label, model_name):
  110. model_key = app_label, model_name
  111. del self.models[model_key]
  112. if self._relations is not None:
  113. self._relations.pop(model_key, None)
  114. # Call list() since _relations can change size during iteration.
  115. for related_model_key, model_relations in list(self._relations.items()):
  116. model_relations.pop(model_key, None)
  117. if not model_relations:
  118. del self._relations[related_model_key]
  119. if "apps" in self.__dict__: # hasattr would cache the property
  120. self.apps.unregister_model(*model_key)
  121. # Need to do this explicitly since unregister_model() doesn't clear
  122. # the cache automatically (#24513)
  123. self.apps.clear_cache()
  124. def rename_model(self, app_label, old_name, new_name):
  125. # Add a new model.
  126. old_name_lower = old_name.lower()
  127. new_name_lower = new_name.lower()
  128. renamed_model = self.models[app_label, old_name_lower].clone()
  129. renamed_model.name = new_name
  130. self.models[app_label, new_name_lower] = renamed_model
  131. # Repoint all fields pointing to the old model to the new one.
  132. old_model_tuple = (app_label, old_name_lower)
  133. new_remote_model = f"{app_label}.{new_name}"
  134. to_reload = set()
  135. for model_state, name, field, reference in get_references(
  136. self, old_model_tuple
  137. ):
  138. changed_field = None
  139. if reference.to:
  140. changed_field = field.clone()
  141. changed_field.remote_field.model = new_remote_model
  142. if reference.through:
  143. if changed_field is None:
  144. changed_field = field.clone()
  145. changed_field.remote_field.through = new_remote_model
  146. if changed_field:
  147. model_state.fields[name] = changed_field
  148. to_reload.add((model_state.app_label, model_state.name_lower))
  149. if self._relations is not None:
  150. old_name_key = app_label, old_name_lower
  151. new_name_key = app_label, new_name_lower
  152. if old_name_key in self._relations:
  153. self._relations[new_name_key] = self._relations.pop(old_name_key)
  154. for model_relations in self._relations.values():
  155. if old_name_key in model_relations:
  156. model_relations[new_name_key] = model_relations.pop(old_name_key)
  157. # Reload models related to old model before removing the old model.
  158. self.reload_models(to_reload, delay=True)
  159. # Remove the old model.
  160. self.remove_model(app_label, old_name_lower)
  161. self.reload_model(app_label, new_name_lower, delay=True)
  162. def alter_model_options(self, app_label, model_name, options, option_keys=None):
  163. model_state = self.models[app_label, model_name]
  164. model_state.options = {**model_state.options, **options}
  165. if option_keys:
  166. for key in option_keys:
  167. if key not in options:
  168. model_state.options.pop(key, False)
  169. self.reload_model(app_label, model_name, delay=True)
  170. def remove_model_options(self, app_label, model_name, option_name, value_to_remove):
  171. model_state = self.models[app_label, model_name]
  172. if objs := model_state.options.get(option_name):
  173. model_state.options[option_name] = [
  174. obj for obj in objs if tuple(obj) != tuple(value_to_remove)
  175. ]
  176. self.reload_model(app_label, model_name, delay=True)
  177. def alter_model_managers(self, app_label, model_name, managers):
  178. model_state = self.models[app_label, model_name]
  179. model_state.managers = list(managers)
  180. self.reload_model(app_label, model_name, delay=True)
  181. def _append_option(self, app_label, model_name, option_name, obj):
  182. model_state = self.models[app_label, model_name]
  183. model_state.options[option_name] = [*model_state.options[option_name], obj]
  184. self.reload_model(app_label, model_name, delay=True)
  185. def _remove_option(self, app_label, model_name, option_name, obj_name):
  186. model_state = self.models[app_label, model_name]
  187. objs = model_state.options[option_name]
  188. model_state.options[option_name] = [obj for obj in objs if obj.name != obj_name]
  189. self.reload_model(app_label, model_name, delay=True)
  190. def add_index(self, app_label, model_name, index):
  191. self._append_option(app_label, model_name, "indexes", index)
  192. def remove_index(self, app_label, model_name, index_name):
  193. self._remove_option(app_label, model_name, "indexes", index_name)
  194. def rename_index(self, app_label, model_name, old_index_name, new_index_name):
  195. model_state = self.models[app_label, model_name]
  196. objs = model_state.options["indexes"]
  197. new_indexes = []
  198. for obj in objs:
  199. if obj.name == old_index_name:
  200. obj = obj.clone()
  201. obj.name = new_index_name
  202. new_indexes.append(obj)
  203. model_state.options["indexes"] = new_indexes
  204. self.reload_model(app_label, model_name, delay=True)
  205. def add_constraint(self, app_label, model_name, constraint):
  206. self._append_option(app_label, model_name, "constraints", constraint)
  207. def remove_constraint(self, app_label, model_name, constraint_name):
  208. self._remove_option(app_label, model_name, "constraints", constraint_name)
  209. def add_field(self, app_label, model_name, name, field, preserve_default):
  210. # If preserve default is off, don't use the default for future state.
  211. if not preserve_default:
  212. field = field.clone()
  213. field.default = NOT_PROVIDED
  214. else:
  215. field = field
  216. model_key = app_label, model_name
  217. self.models[model_key].fields[name] = field
  218. if self._relations is not None:
  219. self.resolve_model_field_relations(model_key, name, field)
  220. # Delay rendering of relationships if it's not a relational field.
  221. delay = not field.is_relation
  222. self.reload_model(*model_key, delay=delay)
  223. def remove_field(self, app_label, model_name, name):
  224. model_key = app_label, model_name
  225. model_state = self.models[model_key]
  226. old_field = model_state.fields.pop(name)
  227. if self._relations is not None:
  228. self.resolve_model_field_relations(model_key, name, old_field)
  229. # Delay rendering of relationships if it's not a relational field.
  230. delay = not old_field.is_relation
  231. self.reload_model(*model_key, delay=delay)
  232. def alter_field(self, app_label, model_name, name, field, preserve_default):
  233. if not preserve_default:
  234. field = field.clone()
  235. field.default = NOT_PROVIDED
  236. else:
  237. field = field
  238. model_key = app_label, model_name
  239. fields = self.models[model_key].fields
  240. if self._relations is not None:
  241. old_field = fields.pop(name)
  242. if old_field.is_relation:
  243. self.resolve_model_field_relations(model_key, name, old_field)
  244. fields[name] = field
  245. if field.is_relation:
  246. self.resolve_model_field_relations(model_key, name, field)
  247. else:
  248. fields[name] = field
  249. # TODO: investigate if old relational fields must be reloaded or if
  250. # it's sufficient if the new field is (#27737).
  251. # Delay rendering of relationships if it's not a relational field and
  252. # not referenced by a foreign key.
  253. delay = not field.is_relation and not field_is_referenced(
  254. self, model_key, (name, field)
  255. )
  256. self.reload_model(*model_key, delay=delay)
  257. def rename_field(self, app_label, model_name, old_name, new_name):
  258. model_key = app_label, model_name
  259. model_state = self.models[model_key]
  260. # Rename the field.
  261. fields = model_state.fields
  262. try:
  263. found = fields.pop(old_name)
  264. except KeyError:
  265. raise FieldDoesNotExist(
  266. f"{app_label}.{model_name} has no field named '{old_name}'"
  267. )
  268. fields[new_name] = found
  269. for field in fields.values():
  270. # Fix from_fields to refer to the new field.
  271. from_fields = getattr(field, "from_fields", None)
  272. if from_fields:
  273. field.from_fields = tuple(
  274. [
  275. new_name if from_field_name == old_name else from_field_name
  276. for from_field_name in from_fields
  277. ]
  278. )
  279. # Fix index/unique_together to refer to the new field.
  280. options = model_state.options
  281. for option in ("index_together", "unique_together"):
  282. if option in options:
  283. options[option] = [
  284. [new_name if n == old_name else n for n in together]
  285. for together in options[option]
  286. ]
  287. # Fix to_fields to refer to the new field.
  288. delay = True
  289. references = get_references(self, model_key, (old_name, found))
  290. for *_, field, reference in references:
  291. delay = False
  292. if reference.to:
  293. remote_field, to_fields = reference.to
  294. if getattr(remote_field, "field_name", None) == old_name:
  295. remote_field.field_name = new_name
  296. if to_fields:
  297. field.to_fields = tuple(
  298. [
  299. new_name if to_field_name == old_name else to_field_name
  300. for to_field_name in to_fields
  301. ]
  302. )
  303. if self._relations is not None:
  304. old_name_lower = old_name.lower()
  305. new_name_lower = new_name.lower()
  306. for to_model in self._relations.values():
  307. if old_name_lower in to_model[model_key]:
  308. field = to_model[model_key].pop(old_name_lower)
  309. field.name = new_name_lower
  310. to_model[model_key][new_name_lower] = field
  311. self.reload_model(*model_key, delay=delay)
  312. def _find_reload_model(self, app_label, model_name, delay=False):
  313. if delay:
  314. self.is_delayed = True
  315. related_models = set()
  316. try:
  317. old_model = self.apps.get_model(app_label, model_name)
  318. except LookupError:
  319. pass
  320. else:
  321. # Get all relations to and from the old model before reloading,
  322. # as _meta.apps may change
  323. if delay:
  324. related_models = get_related_models_tuples(old_model)
  325. else:
  326. related_models = get_related_models_recursive(old_model)
  327. # Get all outgoing references from the model to be rendered
  328. model_state = self.models[(app_label, model_name)]
  329. # Directly related models are the models pointed to by ForeignKeys,
  330. # OneToOneFields, and ManyToManyFields.
  331. direct_related_models = set()
  332. for field in model_state.fields.values():
  333. if field.is_relation:
  334. if field.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT:
  335. continue
  336. rel_app_label, rel_model_name = _get_app_label_and_model_name(
  337. field.related_model, app_label
  338. )
  339. direct_related_models.add((rel_app_label, rel_model_name.lower()))
  340. # For all direct related models recursively get all related models.
  341. related_models.update(direct_related_models)
  342. for rel_app_label, rel_model_name in direct_related_models:
  343. try:
  344. rel_model = self.apps.get_model(rel_app_label, rel_model_name)
  345. except LookupError:
  346. pass
  347. else:
  348. if delay:
  349. related_models.update(get_related_models_tuples(rel_model))
  350. else:
  351. related_models.update(get_related_models_recursive(rel_model))
  352. # Include the model itself
  353. related_models.add((app_label, model_name))
  354. return related_models
  355. def reload_model(self, app_label, model_name, delay=False):
  356. if "apps" in self.__dict__: # hasattr would cache the property
  357. related_models = self._find_reload_model(app_label, model_name, delay)
  358. self._reload(related_models)
  359. def reload_models(self, models, delay=True):
  360. if "apps" in self.__dict__: # hasattr would cache the property
  361. related_models = set()
  362. for app_label, model_name in models:
  363. related_models.update(
  364. self._find_reload_model(app_label, model_name, delay)
  365. )
  366. self._reload(related_models)
  367. def _reload(self, related_models):
  368. # Unregister all related models
  369. with self.apps.bulk_update():
  370. for rel_app_label, rel_model_name in related_models:
  371. self.apps.unregister_model(rel_app_label, rel_model_name)
  372. states_to_be_rendered = []
  373. # Gather all models states of those models that will be rerendered.
  374. # This includes:
  375. # 1. All related models of unmigrated apps
  376. for model_state in self.apps.real_models:
  377. if (model_state.app_label, model_state.name_lower) in related_models:
  378. states_to_be_rendered.append(model_state)
  379. # 2. All related models of migrated apps
  380. for rel_app_label, rel_model_name in related_models:
  381. try:
  382. model_state = self.models[rel_app_label, rel_model_name]
  383. except KeyError:
  384. pass
  385. else:
  386. states_to_be_rendered.append(model_state)
  387. # Render all models
  388. self.apps.render_multiple(states_to_be_rendered)
  389. def update_model_field_relation(
  390. self,
  391. model,
  392. model_key,
  393. field_name,
  394. field,
  395. concretes,
  396. ):
  397. remote_model_key = resolve_relation(model, *model_key)
  398. if remote_model_key[0] not in self.real_apps and remote_model_key in concretes:
  399. remote_model_key = concretes[remote_model_key]
  400. relations_to_remote_model = self._relations[remote_model_key]
  401. if field_name in self.models[model_key].fields:
  402. # The assert holds because it's a new relation, or an altered
  403. # relation, in which case references have been removed by
  404. # alter_field().
  405. assert field_name not in relations_to_remote_model[model_key]
  406. relations_to_remote_model[model_key][field_name] = field
  407. else:
  408. del relations_to_remote_model[model_key][field_name]
  409. if not relations_to_remote_model[model_key]:
  410. del relations_to_remote_model[model_key]
  411. def resolve_model_field_relations(
  412. self,
  413. model_key,
  414. field_name,
  415. field,
  416. concretes=None,
  417. ):
  418. remote_field = field.remote_field
  419. if not remote_field:
  420. return
  421. if concretes is None:
  422. concretes, _ = self._get_concrete_models_mapping_and_proxy_models()
  423. self.update_model_field_relation(
  424. remote_field.model,
  425. model_key,
  426. field_name,
  427. field,
  428. concretes,
  429. )
  430. through = getattr(remote_field, "through", None)
  431. if not through:
  432. return
  433. self.update_model_field_relation(
  434. through, model_key, field_name, field, concretes
  435. )
  436. def resolve_model_relations(self, model_key, concretes=None):
  437. if concretes is None:
  438. concretes, _ = self._get_concrete_models_mapping_and_proxy_models()
  439. model_state = self.models[model_key]
  440. for field_name, field in model_state.fields.items():
  441. self.resolve_model_field_relations(model_key, field_name, field, concretes)
  442. def resolve_fields_and_relations(self):
  443. # Resolve fields.
  444. for model_state in self.models.values():
  445. for field_name, field in model_state.fields.items():
  446. field.name = field_name
  447. # Resolve relations.
  448. # {remote_model_key: {model_key: {field_name: field}}}
  449. self._relations = defaultdict(partial(defaultdict, dict))
  450. concretes, proxies = self._get_concrete_models_mapping_and_proxy_models()
  451. for model_key in concretes:
  452. self.resolve_model_relations(model_key, concretes)
  453. for model_key in proxies:
  454. self._relations[model_key] = self._relations[concretes[model_key]]
  455. def get_concrete_model_key(self, model):
  456. (
  457. concrete_models_mapping,
  458. _,
  459. ) = self._get_concrete_models_mapping_and_proxy_models()
  460. model_key = make_model_tuple(model)
  461. return concrete_models_mapping[model_key]
  462. def _get_concrete_models_mapping_and_proxy_models(self):
  463. concrete_models_mapping = {}
  464. proxy_models = {}
  465. # Split models to proxy and concrete models.
  466. for model_key, model_state in self.models.items():
  467. if model_state.options.get("proxy"):
  468. proxy_models[model_key] = model_state
  469. # Find a concrete model for the proxy.
  470. concrete_models_mapping[
  471. model_key
  472. ] = self._find_concrete_model_from_proxy(
  473. proxy_models,
  474. model_state,
  475. )
  476. else:
  477. concrete_models_mapping[model_key] = model_key
  478. return concrete_models_mapping, proxy_models
  479. def _find_concrete_model_from_proxy(self, proxy_models, model_state):
  480. for base in model_state.bases:
  481. if not (isinstance(base, str) or issubclass(base, models.Model)):
  482. continue
  483. base_key = make_model_tuple(base)
  484. base_state = proxy_models.get(base_key)
  485. if not base_state:
  486. # Concrete model found, stop looking at bases.
  487. return base_key
  488. return self._find_concrete_model_from_proxy(proxy_models, base_state)
  489. def clone(self):
  490. """Return an exact copy of this ProjectState."""
  491. new_state = ProjectState(
  492. models={k: v.clone() for k, v in self.models.items()},
  493. real_apps=self.real_apps,
  494. )
  495. if "apps" in self.__dict__:
  496. new_state.apps = self.apps.clone()
  497. new_state.is_delayed = self.is_delayed
  498. return new_state
  499. def clear_delayed_apps_cache(self):
  500. if self.is_delayed and "apps" in self.__dict__:
  501. del self.__dict__["apps"]
  502. @cached_property
  503. def apps(self):
  504. return StateApps(self.real_apps, self.models)
  505. @classmethod
  506. def from_apps(cls, apps):
  507. """Take an Apps and return a ProjectState matching it."""
  508. app_models = {}
  509. for model in apps.get_models(include_swapped=True):
  510. model_state = ModelState.from_model(model)
  511. app_models[(model_state.app_label, model_state.name_lower)] = model_state
  512. return cls(app_models)
  513. def __eq__(self, other):
  514. return self.models == other.models and self.real_apps == other.real_apps
  515. class AppConfigStub(AppConfig):
  516. """Stub of an AppConfig. Only provides a label and a dict of models."""
  517. def __init__(self, label):
  518. self.apps = None
  519. self.models = {}
  520. # App-label and app-name are not the same thing, so technically passing
  521. # in the label here is wrong. In practice, migrations don't care about
  522. # the app name, but we need something unique, and the label works fine.
  523. self.label = label
  524. self.name = label
  525. def import_models(self):
  526. self.models = self.apps.all_models[self.label]
  527. class StateApps(Apps):
  528. """
  529. Subclass of the global Apps registry class to better handle dynamic model
  530. additions and removals.
  531. """
  532. def __init__(self, real_apps, models, ignore_swappable=False):
  533. # Any apps in self.real_apps should have all their models included
  534. # in the render. We don't use the original model instances as there
  535. # are some variables that refer to the Apps object.
  536. # FKs/M2Ms from real apps are also not included as they just
  537. # mess things up with partial states (due to lack of dependencies)
  538. self.real_models = []
  539. for app_label in real_apps:
  540. app = global_apps.get_app_config(app_label)
  541. for model in app.get_models():
  542. self.real_models.append(ModelState.from_model(model, exclude_rels=True))
  543. # Populate the app registry with a stub for each application.
  544. app_labels = {model_state.app_label for model_state in models.values()}
  545. app_configs = [
  546. AppConfigStub(label) for label in sorted([*real_apps, *app_labels])
  547. ]
  548. super().__init__(app_configs)
  549. # These locks get in the way of copying as implemented in clone(),
  550. # which is called whenever Django duplicates a StateApps before
  551. # updating it.
  552. self._lock = None
  553. self.ready_event = None
  554. self.render_multiple([*models.values(), *self.real_models])
  555. # There shouldn't be any operations pending at this point.
  556. from django.core.checks.model_checks import _check_lazy_references
  557. ignore = (
  558. {make_model_tuple(settings.AUTH_USER_MODEL)} if ignore_swappable else set()
  559. )
  560. errors = _check_lazy_references(self, ignore=ignore)
  561. if errors:
  562. raise ValueError("\n".join(error.msg for error in errors))
  563. @contextmanager
  564. def bulk_update(self):
  565. # Avoid clearing each model's cache for each change. Instead, clear
  566. # all caches when we're finished updating the model instances.
  567. ready = self.ready
  568. self.ready = False
  569. try:
  570. yield
  571. finally:
  572. self.ready = ready
  573. self.clear_cache()
  574. def render_multiple(self, model_states):
  575. # We keep trying to render the models in a loop, ignoring invalid
  576. # base errors, until the size of the unrendered models doesn't
  577. # decrease by at least one, meaning there's a base dependency loop/
  578. # missing base.
  579. if not model_states:
  580. return
  581. # Prevent that all model caches are expired for each render.
  582. with self.bulk_update():
  583. unrendered_models = model_states
  584. while unrendered_models:
  585. new_unrendered_models = []
  586. for model in unrendered_models:
  587. try:
  588. model.render(self)
  589. except InvalidBasesError:
  590. new_unrendered_models.append(model)
  591. if len(new_unrendered_models) == len(unrendered_models):
  592. raise InvalidBasesError(
  593. "Cannot resolve bases for %r\nThis can happen if you are "
  594. "inheriting models from an app with migrations (e.g. "
  595. "contrib.auth)\n in an app with no migrations; see "
  596. "https://docs.djangoproject.com/en/%s/topics/migrations/"
  597. "#dependencies for more"
  598. % (new_unrendered_models, get_docs_version())
  599. )
  600. unrendered_models = new_unrendered_models
  601. def clone(self):
  602. """Return a clone of this registry."""
  603. clone = StateApps([], {})
  604. clone.all_models = copy.deepcopy(self.all_models)
  605. clone.app_configs = copy.deepcopy(self.app_configs)
  606. # Set the pointer to the correct app registry.
  607. for app_config in clone.app_configs.values():
  608. app_config.apps = clone
  609. # No need to actually clone them, they'll never change
  610. clone.real_models = self.real_models
  611. return clone
  612. def register_model(self, app_label, model):
  613. self.all_models[app_label][model._meta.model_name] = model
  614. if app_label not in self.app_configs:
  615. self.app_configs[app_label] = AppConfigStub(app_label)
  616. self.app_configs[app_label].apps = self
  617. self.app_configs[app_label].models[model._meta.model_name] = model
  618. self.do_pending_operations(model)
  619. self.clear_cache()
  620. def unregister_model(self, app_label, model_name):
  621. try:
  622. del self.all_models[app_label][model_name]
  623. del self.app_configs[app_label].models[model_name]
  624. except KeyError:
  625. pass
  626. class ModelState:
  627. """
  628. Represent a Django Model. Don't use the actual Model class as it's not
  629. designed to have its options changed - instead, mutate this one and then
  630. render it into a Model as required.
  631. Note that while you are allowed to mutate .fields, you are not allowed
  632. to mutate the Field instances inside there themselves - you must instead
  633. assign new ones, as these are not detached during a clone.
  634. """
  635. def __init__(
  636. self, app_label, name, fields, options=None, bases=None, managers=None
  637. ):
  638. self.app_label = app_label
  639. self.name = name
  640. self.fields = dict(fields)
  641. self.options = options or {}
  642. self.options.setdefault("indexes", [])
  643. self.options.setdefault("constraints", [])
  644. self.bases = bases or (models.Model,)
  645. self.managers = managers or []
  646. for name, field in self.fields.items():
  647. # Sanity-check that fields are NOT already bound to a model.
  648. if hasattr(field, "model"):
  649. raise ValueError(
  650. 'ModelState.fields cannot be bound to a model - "%s" is.' % name
  651. )
  652. # Sanity-check that relation fields are NOT referring to a model class.
  653. if field.is_relation and hasattr(field.related_model, "_meta"):
  654. raise ValueError(
  655. 'ModelState.fields cannot refer to a model class - "%s.to" does. '
  656. "Use a string reference instead." % name
  657. )
  658. if field.many_to_many and hasattr(field.remote_field.through, "_meta"):
  659. raise ValueError(
  660. 'ModelState.fields cannot refer to a model class - "%s.through" '
  661. "does. Use a string reference instead." % name
  662. )
  663. # Sanity-check that indexes have their name set.
  664. for index in self.options["indexes"]:
  665. if not index.name:
  666. raise ValueError(
  667. "Indexes passed to ModelState require a name attribute. "
  668. "%r doesn't have one." % index
  669. )
  670. @cached_property
  671. def name_lower(self):
  672. return self.name.lower()
  673. def get_field(self, field_name):
  674. if field_name == "_order":
  675. field_name = self.options.get("order_with_respect_to", field_name)
  676. return self.fields[field_name]
  677. @classmethod
  678. def from_model(cls, model, exclude_rels=False):
  679. """Given a model, return a ModelState representing it."""
  680. # Deconstruct the fields
  681. fields = []
  682. for field in model._meta.local_fields:
  683. if getattr(field, "remote_field", None) and exclude_rels:
  684. continue
  685. if isinstance(field, models.OrderWrt):
  686. continue
  687. name = field.name
  688. try:
  689. fields.append((name, field.clone()))
  690. except TypeError as e:
  691. raise TypeError(
  692. "Couldn't reconstruct field %s on %s: %s"
  693. % (
  694. name,
  695. model._meta.label,
  696. e,
  697. )
  698. )
  699. if not exclude_rels:
  700. for field in model._meta.local_many_to_many:
  701. name = field.name
  702. try:
  703. fields.append((name, field.clone()))
  704. except TypeError as e:
  705. raise TypeError(
  706. "Couldn't reconstruct m2m field %s on %s: %s"
  707. % (
  708. name,
  709. model._meta.object_name,
  710. e,
  711. )
  712. )
  713. # Extract the options
  714. options = {}
  715. for name in DEFAULT_NAMES:
  716. # Ignore some special options
  717. if name in ["apps", "app_label"]:
  718. continue
  719. elif name in model._meta.original_attrs:
  720. if name == "unique_together":
  721. ut = model._meta.original_attrs["unique_together"]
  722. options[name] = set(normalize_together(ut))
  723. elif name == "index_together":
  724. it = model._meta.original_attrs["index_together"]
  725. options[name] = set(normalize_together(it))
  726. elif name == "indexes":
  727. indexes = [idx.clone() for idx in model._meta.indexes]
  728. for index in indexes:
  729. if not index.name:
  730. index.set_name_with_model(model)
  731. options["indexes"] = indexes
  732. elif name == "constraints":
  733. options["constraints"] = [
  734. con.clone() for con in model._meta.constraints
  735. ]
  736. else:
  737. options[name] = model._meta.original_attrs[name]
  738. # If we're ignoring relationships, remove all field-listing model
  739. # options (that option basically just means "make a stub model")
  740. if exclude_rels:
  741. for key in ["unique_together", "index_together", "order_with_respect_to"]:
  742. if key in options:
  743. del options[key]
  744. # Private fields are ignored, so remove options that refer to them.
  745. elif options.get("order_with_respect_to") in {
  746. field.name for field in model._meta.private_fields
  747. }:
  748. del options["order_with_respect_to"]
  749. def flatten_bases(model):
  750. bases = []
  751. for base in model.__bases__:
  752. if hasattr(base, "_meta") and base._meta.abstract:
  753. bases.extend(flatten_bases(base))
  754. else:
  755. bases.append(base)
  756. return bases
  757. # We can't rely on __mro__ directly because we only want to flatten
  758. # abstract models and not the whole tree. However by recursing on
  759. # __bases__ we may end up with duplicates and ordering issues, we
  760. # therefore discard any duplicates and reorder the bases according
  761. # to their index in the MRO.
  762. flattened_bases = sorted(
  763. set(flatten_bases(model)), key=lambda x: model.__mro__.index(x)
  764. )
  765. # Make our record
  766. bases = tuple(
  767. (base._meta.label_lower if hasattr(base, "_meta") else base)
  768. for base in flattened_bases
  769. )
  770. # Ensure at least one base inherits from models.Model
  771. if not any(
  772. (isinstance(base, str) or issubclass(base, models.Model)) for base in bases
  773. ):
  774. bases = (models.Model,)
  775. managers = []
  776. manager_names = set()
  777. default_manager_shim = None
  778. for manager in model._meta.managers:
  779. if manager.name in manager_names:
  780. # Skip overridden managers.
  781. continue
  782. elif manager.use_in_migrations:
  783. # Copy managers usable in migrations.
  784. new_manager = copy.copy(manager)
  785. new_manager._set_creation_counter()
  786. elif manager is model._base_manager or manager is model._default_manager:
  787. # Shim custom managers used as default and base managers.
  788. new_manager = models.Manager()
  789. new_manager.model = manager.model
  790. new_manager.name = manager.name
  791. if manager is model._default_manager:
  792. default_manager_shim = new_manager
  793. else:
  794. continue
  795. manager_names.add(manager.name)
  796. managers.append((manager.name, new_manager))
  797. # Ignore a shimmed default manager called objects if it's the only one.
  798. if managers == [("objects", default_manager_shim)]:
  799. managers = []
  800. # Construct the new ModelState
  801. return cls(
  802. model._meta.app_label,
  803. model._meta.object_name,
  804. fields,
  805. options,
  806. bases,
  807. managers,
  808. )
  809. def construct_managers(self):
  810. """Deep-clone the managers using deconstruction."""
  811. # Sort all managers by their creation counter
  812. sorted_managers = sorted(self.managers, key=lambda v: v[1].creation_counter)
  813. for mgr_name, manager in sorted_managers:
  814. as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct()
  815. if as_manager:
  816. qs_class = import_string(qs_path)
  817. yield mgr_name, qs_class.as_manager()
  818. else:
  819. manager_class = import_string(manager_path)
  820. yield mgr_name, manager_class(*args, **kwargs)
  821. def clone(self):
  822. """Return an exact copy of this ModelState."""
  823. return self.__class__(
  824. app_label=self.app_label,
  825. name=self.name,
  826. fields=dict(self.fields),
  827. # Since options are shallow-copied here, operations such as
  828. # AddIndex must replace their option (e.g 'indexes') rather
  829. # than mutating it.
  830. options=dict(self.options),
  831. bases=self.bases,
  832. managers=list(self.managers),
  833. )
  834. def render(self, apps):
  835. """Create a Model object from our current state into the given apps."""
  836. # First, make a Meta object
  837. meta_contents = {"app_label": self.app_label, "apps": apps, **self.options}
  838. meta = type("Meta", (), meta_contents)
  839. # Then, work out our bases
  840. try:
  841. bases = tuple(
  842. (apps.get_model(base) if isinstance(base, str) else base)
  843. for base in self.bases
  844. )
  845. except LookupError:
  846. raise InvalidBasesError(
  847. "Cannot resolve one or more bases from %r" % (self.bases,)
  848. )
  849. # Clone fields for the body, add other bits.
  850. body = {name: field.clone() for name, field in self.fields.items()}
  851. body["Meta"] = meta
  852. body["__module__"] = "__fake__"
  853. # Restore managers
  854. body.update(self.construct_managers())
  855. # Then, make a Model object (apps.register_model is called in __new__)
  856. return type(self.name, bases, body)
  857. def get_index_by_name(self, name):
  858. for index in self.options["indexes"]:
  859. if index.name == name:
  860. return index
  861. raise ValueError("No index named %s on model %s" % (name, self.name))
  862. def get_constraint_by_name(self, name):
  863. for constraint in self.options["constraints"]:
  864. if constraint.name == name:
  865. return constraint
  866. raise ValueError("No constraint named %s on model %s" % (name, self.name))
  867. def __repr__(self):
  868. return "<%s: '%s.%s'>" % (self.__class__.__name__, self.app_label, self.name)
  869. def __eq__(self, other):
  870. return (
  871. (self.app_label == other.app_label)
  872. and (self.name == other.name)
  873. and (len(self.fields) == len(other.fields))
  874. and all(
  875. k1 == k2 and f1.deconstruct()[1:] == f2.deconstruct()[1:]
  876. for (k1, f1), (k2, f2) in zip(
  877. sorted(self.fields.items()),
  878. sorted(other.fields.items()),
  879. )
  880. )
  881. and (self.options == other.options)
  882. and (self.bases == other.bases)
  883. and (self.managers == other.managers)
  884. )