options.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. import bisect
  2. import copy
  3. import inspect
  4. import warnings
  5. from collections import defaultdict
  6. from django.apps import apps
  7. from django.conf import settings
  8. from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
  9. from django.db import connections
  10. from django.db.models import AutoField, Manager, OrderWrt, UniqueConstraint
  11. from django.db.models.query_utils import PathInfo
  12. from django.utils.datastructures import ImmutableList, OrderedSet
  13. from django.utils.deprecation import RemovedInDjango51Warning
  14. from django.utils.functional import cached_property
  15. from django.utils.module_loading import import_string
  16. from django.utils.text import camel_case_to_spaces, format_lazy
  17. from django.utils.translation import override
  18. PROXY_PARENTS = object()
  19. EMPTY_RELATION_TREE = ()
  20. IMMUTABLE_WARNING = (
  21. "The return type of '%s' should never be mutated. If you want to manipulate this "
  22. "list for your own use, make a copy first."
  23. )
  24. DEFAULT_NAMES = (
  25. "verbose_name",
  26. "verbose_name_plural",
  27. "db_table",
  28. "db_table_comment",
  29. "ordering",
  30. "unique_together",
  31. "permissions",
  32. "get_latest_by",
  33. "order_with_respect_to",
  34. "app_label",
  35. "db_tablespace",
  36. "abstract",
  37. "managed",
  38. "proxy",
  39. "swappable",
  40. "auto_created",
  41. "index_together", # RemovedInDjango51Warning.
  42. "apps",
  43. "default_permissions",
  44. "select_on_save",
  45. "default_related_name",
  46. "required_db_features",
  47. "required_db_vendor",
  48. "base_manager_name",
  49. "default_manager_name",
  50. "indexes",
  51. "constraints",
  52. )
  53. def normalize_together(option_together):
  54. """
  55. option_together can be either a tuple of tuples, or a single
  56. tuple of two strings. Normalize it to a tuple of tuples, so that
  57. calling code can uniformly expect that.
  58. """
  59. try:
  60. if not option_together:
  61. return ()
  62. if not isinstance(option_together, (tuple, list)):
  63. raise TypeError
  64. first_element = option_together[0]
  65. if not isinstance(first_element, (tuple, list)):
  66. option_together = (option_together,)
  67. # Normalize everything to tuples
  68. return tuple(tuple(ot) for ot in option_together)
  69. except TypeError:
  70. # If the value of option_together isn't valid, return it
  71. # verbatim; this will be picked up by the check framework later.
  72. return option_together
  73. def make_immutable_fields_list(name, data):
  74. return ImmutableList(data, warning=IMMUTABLE_WARNING % name)
  75. class Options:
  76. FORWARD_PROPERTIES = {
  77. "fields",
  78. "many_to_many",
  79. "concrete_fields",
  80. "local_concrete_fields",
  81. "_non_pk_concrete_field_names",
  82. "_reverse_one_to_one_field_names",
  83. "_forward_fields_map",
  84. "managers",
  85. "managers_map",
  86. "base_manager",
  87. "default_manager",
  88. }
  89. REVERSE_PROPERTIES = {"related_objects", "fields_map", "_relation_tree"}
  90. default_apps = apps
  91. def __init__(self, meta, app_label=None):
  92. self._get_fields_cache = {}
  93. self.local_fields = []
  94. self.local_many_to_many = []
  95. self.private_fields = []
  96. self.local_managers = []
  97. self.base_manager_name = None
  98. self.default_manager_name = None
  99. self.model_name = None
  100. self.verbose_name = None
  101. self.verbose_name_plural = None
  102. self.db_table = ""
  103. self.db_table_comment = ""
  104. self.ordering = []
  105. self._ordering_clash = False
  106. self.indexes = []
  107. self.constraints = []
  108. self.unique_together = []
  109. self.index_together = [] # RemovedInDjango51Warning.
  110. self.select_on_save = False
  111. self.default_permissions = ("add", "change", "delete", "view")
  112. self.permissions = []
  113. self.object_name = None
  114. self.app_label = app_label
  115. self.get_latest_by = None
  116. self.order_with_respect_to = None
  117. self.db_tablespace = settings.DEFAULT_TABLESPACE
  118. self.required_db_features = []
  119. self.required_db_vendor = None
  120. self.meta = meta
  121. self.pk = None
  122. self.auto_field = None
  123. self.abstract = False
  124. self.managed = True
  125. self.proxy = False
  126. # For any class that is a proxy (including automatically created
  127. # classes for deferred object loading), proxy_for_model tells us
  128. # which class this model is proxying. Note that proxy_for_model
  129. # can create a chain of proxy models. For non-proxy models, the
  130. # variable is always None.
  131. self.proxy_for_model = None
  132. # For any non-abstract class, the concrete class is the model
  133. # in the end of the proxy_for_model chain. In particular, for
  134. # concrete models, the concrete_model is always the class itself.
  135. self.concrete_model = None
  136. self.swappable = None
  137. self.parents = {}
  138. self.auto_created = False
  139. # List of all lookups defined in ForeignKey 'limit_choices_to' options
  140. # from *other* models. Needed for some admin checks. Internal use only.
  141. self.related_fkey_lookups = []
  142. # A custom app registry to use, if you're making a separate model set.
  143. self.apps = self.default_apps
  144. self.default_related_name = None
  145. @property
  146. def label(self):
  147. return "%s.%s" % (self.app_label, self.object_name)
  148. @property
  149. def label_lower(self):
  150. return "%s.%s" % (self.app_label, self.model_name)
  151. @property
  152. def app_config(self):
  153. # Don't go through get_app_config to avoid triggering imports.
  154. return self.apps.app_configs.get(self.app_label)
  155. def contribute_to_class(self, cls, name):
  156. from django.db import connection
  157. from django.db.backends.utils import truncate_name
  158. cls._meta = self
  159. self.model = cls
  160. # First, construct the default values for these options.
  161. self.object_name = cls.__name__
  162. self.model_name = self.object_name.lower()
  163. self.verbose_name = camel_case_to_spaces(self.object_name)
  164. # Store the original user-defined values for each option,
  165. # for use when serializing the model definition
  166. self.original_attrs = {}
  167. # Next, apply any overridden values from 'class Meta'.
  168. if self.meta:
  169. meta_attrs = self.meta.__dict__.copy()
  170. for name in self.meta.__dict__:
  171. # Ignore any private attributes that Django doesn't care about.
  172. # NOTE: We can't modify a dictionary's contents while looping
  173. # over it, so we loop over the *original* dictionary instead.
  174. if name.startswith("_"):
  175. del meta_attrs[name]
  176. for attr_name in DEFAULT_NAMES:
  177. if attr_name in meta_attrs:
  178. setattr(self, attr_name, meta_attrs.pop(attr_name))
  179. self.original_attrs[attr_name] = getattr(self, attr_name)
  180. elif hasattr(self.meta, attr_name):
  181. setattr(self, attr_name, getattr(self.meta, attr_name))
  182. self.original_attrs[attr_name] = getattr(self, attr_name)
  183. self.unique_together = normalize_together(self.unique_together)
  184. self.index_together = normalize_together(self.index_together)
  185. if self.index_together:
  186. warnings.warn(
  187. f"'index_together' is deprecated. Use 'Meta.indexes' in "
  188. f"{self.label!r} instead.",
  189. RemovedInDjango51Warning,
  190. )
  191. # App label/class name interpolation for names of constraints and
  192. # indexes.
  193. if not getattr(cls._meta, "abstract", False):
  194. for attr_name in {"constraints", "indexes"}:
  195. objs = getattr(self, attr_name, [])
  196. setattr(self, attr_name, self._format_names_with_class(cls, objs))
  197. # verbose_name_plural is a special case because it uses a 's'
  198. # by default.
  199. if self.verbose_name_plural is None:
  200. self.verbose_name_plural = format_lazy("{}s", self.verbose_name)
  201. # order_with_respect_and ordering are mutually exclusive.
  202. self._ordering_clash = bool(self.ordering and self.order_with_respect_to)
  203. # Any leftover attributes must be invalid.
  204. if meta_attrs != {}:
  205. raise TypeError(
  206. "'class Meta' got invalid attribute(s): %s" % ",".join(meta_attrs)
  207. )
  208. else:
  209. self.verbose_name_plural = format_lazy("{}s", self.verbose_name)
  210. del self.meta
  211. # If the db_table wasn't provided, use the app_label + model_name.
  212. if not self.db_table:
  213. self.db_table = "%s_%s" % (self.app_label, self.model_name)
  214. self.db_table = truncate_name(
  215. self.db_table, connection.ops.max_name_length()
  216. )
  217. def _format_names_with_class(self, cls, objs):
  218. """App label/class name interpolation for object names."""
  219. new_objs = []
  220. for obj in objs:
  221. obj = obj.clone()
  222. obj.name = obj.name % {
  223. "app_label": cls._meta.app_label.lower(),
  224. "class": cls.__name__.lower(),
  225. }
  226. new_objs.append(obj)
  227. return new_objs
  228. def _get_default_pk_class(self):
  229. pk_class_path = getattr(
  230. self.app_config,
  231. "default_auto_field",
  232. settings.DEFAULT_AUTO_FIELD,
  233. )
  234. if self.app_config and self.app_config._is_default_auto_field_overridden:
  235. app_config_class = type(self.app_config)
  236. source = (
  237. f"{app_config_class.__module__}."
  238. f"{app_config_class.__qualname__}.default_auto_field"
  239. )
  240. else:
  241. source = "DEFAULT_AUTO_FIELD"
  242. if not pk_class_path:
  243. raise ImproperlyConfigured(f"{source} must not be empty.")
  244. try:
  245. pk_class = import_string(pk_class_path)
  246. except ImportError as e:
  247. msg = (
  248. f"{source} refers to the module '{pk_class_path}' that could "
  249. f"not be imported."
  250. )
  251. raise ImproperlyConfigured(msg) from e
  252. if not issubclass(pk_class, AutoField):
  253. raise ValueError(
  254. f"Primary key '{pk_class_path}' referred by {source} must "
  255. f"subclass AutoField."
  256. )
  257. return pk_class
  258. def _prepare(self, model):
  259. if self.order_with_respect_to:
  260. # The app registry will not be ready at this point, so we cannot
  261. # use get_field().
  262. query = self.order_with_respect_to
  263. try:
  264. self.order_with_respect_to = next(
  265. f
  266. for f in self._get_fields(reverse=False)
  267. if f.name == query or f.attname == query
  268. )
  269. except StopIteration:
  270. raise FieldDoesNotExist(
  271. "%s has no field named '%s'" % (self.object_name, query)
  272. )
  273. self.ordering = ("_order",)
  274. if not any(
  275. isinstance(field, OrderWrt) for field in model._meta.local_fields
  276. ):
  277. model.add_to_class("_order", OrderWrt())
  278. else:
  279. self.order_with_respect_to = None
  280. if self.pk is None:
  281. if self.parents:
  282. # Promote the first parent link in lieu of adding yet another
  283. # field.
  284. field = next(iter(self.parents.values()))
  285. # Look for a local field with the same name as the
  286. # first parent link. If a local field has already been
  287. # created, use it instead of promoting the parent
  288. already_created = [
  289. fld for fld in self.local_fields if fld.name == field.name
  290. ]
  291. if already_created:
  292. field = already_created[0]
  293. field.primary_key = True
  294. self.setup_pk(field)
  295. else:
  296. pk_class = self._get_default_pk_class()
  297. auto = pk_class(verbose_name="ID", primary_key=True, auto_created=True)
  298. model.add_to_class("id", auto)
  299. def add_manager(self, manager):
  300. self.local_managers.append(manager)
  301. self._expire_cache()
  302. def add_field(self, field, private=False):
  303. # Insert the given field in the order in which it was created, using
  304. # the "creation_counter" attribute of the field.
  305. # Move many-to-many related fields from self.fields into
  306. # self.many_to_many.
  307. if private:
  308. self.private_fields.append(field)
  309. elif field.is_relation and field.many_to_many:
  310. bisect.insort(self.local_many_to_many, field)
  311. else:
  312. bisect.insort(self.local_fields, field)
  313. self.setup_pk(field)
  314. # If the field being added is a relation to another known field,
  315. # expire the cache on this field and the forward cache on the field
  316. # being referenced, because there will be new relationships in the
  317. # cache. Otherwise, expire the cache of references *to* this field.
  318. # The mechanism for getting at the related model is slightly odd -
  319. # ideally, we'd just ask for field.related_model. However, related_model
  320. # is a cached property, and all the models haven't been loaded yet, so
  321. # we need to make sure we don't cache a string reference.
  322. if (
  323. field.is_relation
  324. and hasattr(field.remote_field, "model")
  325. and field.remote_field.model
  326. ):
  327. try:
  328. field.remote_field.model._meta._expire_cache(forward=False)
  329. except AttributeError:
  330. pass
  331. self._expire_cache()
  332. else:
  333. self._expire_cache(reverse=False)
  334. def setup_pk(self, field):
  335. if not self.pk and field.primary_key:
  336. self.pk = field
  337. field.serialize = False
  338. def setup_proxy(self, target):
  339. """
  340. Do the internal setup so that the current model is a proxy for
  341. "target".
  342. """
  343. self.pk = target._meta.pk
  344. self.proxy_for_model = target
  345. self.db_table = target._meta.db_table
  346. def __repr__(self):
  347. return "<Options for %s>" % self.object_name
  348. def __str__(self):
  349. return self.label_lower
  350. def can_migrate(self, connection):
  351. """
  352. Return True if the model can/should be migrated on the `connection`.
  353. `connection` can be either a real connection or a connection alias.
  354. """
  355. if self.proxy or self.swapped or not self.managed:
  356. return False
  357. if isinstance(connection, str):
  358. connection = connections[connection]
  359. if self.required_db_vendor:
  360. return self.required_db_vendor == connection.vendor
  361. if self.required_db_features:
  362. return all(
  363. getattr(connection.features, feat, False)
  364. for feat in self.required_db_features
  365. )
  366. return True
  367. @property
  368. def verbose_name_raw(self):
  369. """Return the untranslated verbose name."""
  370. with override(None):
  371. return str(self.verbose_name)
  372. @property
  373. def swapped(self):
  374. """
  375. Has this model been swapped out for another? If so, return the model
  376. name of the replacement; otherwise, return None.
  377. For historical reasons, model name lookups using get_model() are
  378. case insensitive, so we make sure we are case insensitive here.
  379. """
  380. if self.swappable:
  381. swapped_for = getattr(settings, self.swappable, None)
  382. if swapped_for:
  383. try:
  384. swapped_label, swapped_object = swapped_for.split(".")
  385. except ValueError:
  386. # setting not in the format app_label.model_name
  387. # raising ImproperlyConfigured here causes problems with
  388. # test cleanup code - instead it is raised in get_user_model
  389. # or as part of validation.
  390. return swapped_for
  391. if (
  392. "%s.%s" % (swapped_label, swapped_object.lower())
  393. != self.label_lower
  394. ):
  395. return swapped_for
  396. return None
  397. @cached_property
  398. def managers(self):
  399. managers = []
  400. seen_managers = set()
  401. bases = (b for b in self.model.mro() if hasattr(b, "_meta"))
  402. for depth, base in enumerate(bases):
  403. for manager in base._meta.local_managers:
  404. if manager.name in seen_managers:
  405. continue
  406. manager = copy.copy(manager)
  407. manager.model = self.model
  408. seen_managers.add(manager.name)
  409. managers.append((depth, manager.creation_counter, manager))
  410. return make_immutable_fields_list(
  411. "managers",
  412. (m[2] for m in sorted(managers)),
  413. )
  414. @cached_property
  415. def managers_map(self):
  416. return {manager.name: manager for manager in self.managers}
  417. @cached_property
  418. def base_manager(self):
  419. base_manager_name = self.base_manager_name
  420. if not base_manager_name:
  421. # Get the first parent's base_manager_name if there's one.
  422. for parent in self.model.mro()[1:]:
  423. if hasattr(parent, "_meta"):
  424. if parent._base_manager.name != "_base_manager":
  425. base_manager_name = parent._base_manager.name
  426. break
  427. if base_manager_name:
  428. try:
  429. return self.managers_map[base_manager_name]
  430. except KeyError:
  431. raise ValueError(
  432. "%s has no manager named %r"
  433. % (
  434. self.object_name,
  435. base_manager_name,
  436. )
  437. )
  438. manager = Manager()
  439. manager.name = "_base_manager"
  440. manager.model = self.model
  441. manager.auto_created = True
  442. return manager
  443. @cached_property
  444. def default_manager(self):
  445. default_manager_name = self.default_manager_name
  446. if not default_manager_name and not self.local_managers:
  447. # Get the first parent's default_manager_name if there's one.
  448. for parent in self.model.mro()[1:]:
  449. if hasattr(parent, "_meta"):
  450. default_manager_name = parent._meta.default_manager_name
  451. break
  452. if default_manager_name:
  453. try:
  454. return self.managers_map[default_manager_name]
  455. except KeyError:
  456. raise ValueError(
  457. "%s has no manager named %r"
  458. % (
  459. self.object_name,
  460. default_manager_name,
  461. )
  462. )
  463. if self.managers:
  464. return self.managers[0]
  465. @cached_property
  466. def fields(self):
  467. """
  468. Return a list of all forward fields on the model and its parents,
  469. excluding ManyToManyFields.
  470. Private API intended only to be used by Django itself; get_fields()
  471. combined with filtering of field properties is the public API for
  472. obtaining this field list.
  473. """
  474. # For legacy reasons, the fields property should only contain forward
  475. # fields that are not private or with a m2m cardinality. Therefore we
  476. # pass these three filters as filters to the generator.
  477. # The third lambda is a longwinded way of checking f.related_model - we don't
  478. # use that property directly because related_model is a cached property,
  479. # and all the models may not have been loaded yet; we don't want to cache
  480. # the string reference to the related_model.
  481. def is_not_an_m2m_field(f):
  482. return not (f.is_relation and f.many_to_many)
  483. def is_not_a_generic_relation(f):
  484. return not (f.is_relation and f.one_to_many)
  485. def is_not_a_generic_foreign_key(f):
  486. return not (
  487. f.is_relation
  488. and f.many_to_one
  489. and not (hasattr(f.remote_field, "model") and f.remote_field.model)
  490. )
  491. return make_immutable_fields_list(
  492. "fields",
  493. (
  494. f
  495. for f in self._get_fields(reverse=False)
  496. if is_not_an_m2m_field(f)
  497. and is_not_a_generic_relation(f)
  498. and is_not_a_generic_foreign_key(f)
  499. ),
  500. )
  501. @cached_property
  502. def concrete_fields(self):
  503. """
  504. Return a list of all concrete fields on the model and its parents.
  505. Private API intended only to be used by Django itself; get_fields()
  506. combined with filtering of field properties is the public API for
  507. obtaining this field list.
  508. """
  509. return make_immutable_fields_list(
  510. "concrete_fields", (f for f in self.fields if f.concrete)
  511. )
  512. @cached_property
  513. def local_concrete_fields(self):
  514. """
  515. Return a list of all concrete fields on the model.
  516. Private API intended only to be used by Django itself; get_fields()
  517. combined with filtering of field properties is the public API for
  518. obtaining this field list.
  519. """
  520. return make_immutable_fields_list(
  521. "local_concrete_fields", (f for f in self.local_fields if f.concrete)
  522. )
  523. @cached_property
  524. def many_to_many(self):
  525. """
  526. Return a list of all many to many fields on the model and its parents.
  527. Private API intended only to be used by Django itself; get_fields()
  528. combined with filtering of field properties is the public API for
  529. obtaining this list.
  530. """
  531. return make_immutable_fields_list(
  532. "many_to_many",
  533. (
  534. f
  535. for f in self._get_fields(reverse=False)
  536. if f.is_relation and f.many_to_many
  537. ),
  538. )
  539. @cached_property
  540. def related_objects(self):
  541. """
  542. Return all related objects pointing to the current model. The related
  543. objects can come from a one-to-one, one-to-many, or many-to-many field
  544. relation type.
  545. Private API intended only to be used by Django itself; get_fields()
  546. combined with filtering of field properties is the public API for
  547. obtaining this field list.
  548. """
  549. all_related_fields = self._get_fields(
  550. forward=False, reverse=True, include_hidden=True
  551. )
  552. return make_immutable_fields_list(
  553. "related_objects",
  554. (
  555. obj
  556. for obj in all_related_fields
  557. if not obj.hidden or obj.field.many_to_many
  558. ),
  559. )
  560. @cached_property
  561. def _forward_fields_map(self):
  562. res = {}
  563. fields = self._get_fields(reverse=False)
  564. for field in fields:
  565. res[field.name] = field
  566. # Due to the way Django's internals work, get_field() should also
  567. # be able to fetch a field by attname. In the case of a concrete
  568. # field with relation, includes the *_id name too
  569. try:
  570. res[field.attname] = field
  571. except AttributeError:
  572. pass
  573. return res
  574. @cached_property
  575. def fields_map(self):
  576. res = {}
  577. fields = self._get_fields(forward=False, include_hidden=True)
  578. for field in fields:
  579. res[field.name] = field
  580. # Due to the way Django's internals work, get_field() should also
  581. # be able to fetch a field by attname. In the case of a concrete
  582. # field with relation, includes the *_id name too
  583. try:
  584. res[field.attname] = field
  585. except AttributeError:
  586. pass
  587. return res
  588. def get_field(self, field_name):
  589. """
  590. Return a field instance given the name of a forward or reverse field.
  591. """
  592. try:
  593. # In order to avoid premature loading of the relation tree
  594. # (expensive) we prefer checking if the field is a forward field.
  595. return self._forward_fields_map[field_name]
  596. except KeyError:
  597. # If the app registry is not ready, reverse fields are
  598. # unavailable, therefore we throw a FieldDoesNotExist exception.
  599. if not self.apps.models_ready:
  600. raise FieldDoesNotExist(
  601. "%s has no field named '%s'. The app cache isn't ready yet, "
  602. "so if this is an auto-created related field, it won't "
  603. "be available yet." % (self.object_name, field_name)
  604. )
  605. try:
  606. # Retrieve field instance by name from cached or just-computed
  607. # field map.
  608. return self.fields_map[field_name]
  609. except KeyError:
  610. raise FieldDoesNotExist(
  611. "%s has no field named '%s'" % (self.object_name, field_name)
  612. )
  613. def get_base_chain(self, model):
  614. """
  615. Return a list of parent classes leading to `model` (ordered from
  616. closest to most distant ancestor). This has to handle the case where
  617. `model` is a grandparent or even more distant relation.
  618. """
  619. if not self.parents:
  620. return []
  621. if model in self.parents:
  622. return [model]
  623. for parent in self.parents:
  624. res = parent._meta.get_base_chain(model)
  625. if res:
  626. res.insert(0, parent)
  627. return res
  628. return []
  629. def get_parent_list(self):
  630. """
  631. Return all the ancestors of this model as a list ordered by MRO.
  632. Useful for determining if something is an ancestor, regardless of lineage.
  633. """
  634. result = OrderedSet(self.parents)
  635. for parent in self.parents:
  636. for ancestor in parent._meta.get_parent_list():
  637. result.add(ancestor)
  638. return list(result)
  639. def get_ancestor_link(self, ancestor):
  640. """
  641. Return the field on the current model which points to the given
  642. "ancestor". This is possible an indirect link (a pointer to a parent
  643. model, which points, eventually, to the ancestor). Used when
  644. constructing table joins for model inheritance.
  645. Return None if the model isn't an ancestor of this one.
  646. """
  647. if ancestor in self.parents:
  648. return self.parents[ancestor]
  649. for parent in self.parents:
  650. # Tries to get a link field from the immediate parent
  651. parent_link = parent._meta.get_ancestor_link(ancestor)
  652. if parent_link:
  653. # In case of a proxied model, the first link
  654. # of the chain to the ancestor is that parent
  655. # links
  656. return self.parents[parent] or parent_link
  657. def get_path_to_parent(self, parent):
  658. """
  659. Return a list of PathInfos containing the path from the current
  660. model to the parent model, or an empty list if parent is not a
  661. parent of the current model.
  662. """
  663. if self.model is parent:
  664. return []
  665. # Skip the chain of proxy to the concrete proxied model.
  666. proxied_model = self.concrete_model
  667. path = []
  668. opts = self
  669. for int_model in self.get_base_chain(parent):
  670. if int_model is proxied_model:
  671. opts = int_model._meta
  672. else:
  673. final_field = opts.parents[int_model]
  674. targets = (final_field.remote_field.get_related_field(),)
  675. opts = int_model._meta
  676. path.append(
  677. PathInfo(
  678. from_opts=final_field.model._meta,
  679. to_opts=opts,
  680. target_fields=targets,
  681. join_field=final_field,
  682. m2m=False,
  683. direct=True,
  684. filtered_relation=None,
  685. )
  686. )
  687. return path
  688. def get_path_from_parent(self, parent):
  689. """
  690. Return a list of PathInfos containing the path from the parent
  691. model to the current model, or an empty list if parent is not a
  692. parent of the current model.
  693. """
  694. if self.model is parent:
  695. return []
  696. model = self.concrete_model
  697. # Get a reversed base chain including both the current and parent
  698. # models.
  699. chain = model._meta.get_base_chain(parent)
  700. chain.reverse()
  701. chain.append(model)
  702. # Construct a list of the PathInfos between models in chain.
  703. path = []
  704. for i, ancestor in enumerate(chain[:-1]):
  705. child = chain[i + 1]
  706. link = child._meta.get_ancestor_link(ancestor)
  707. path.extend(link.reverse_path_infos)
  708. return path
  709. def _populate_directed_relation_graph(self):
  710. """
  711. This method is used by each model to find its reverse objects. As this
  712. method is very expensive and is accessed frequently (it looks up every
  713. field in a model, in every app), it is computed on first access and then
  714. is set as a property on every model.
  715. """
  716. related_objects_graph = defaultdict(list)
  717. all_models = self.apps.get_models(include_auto_created=True)
  718. for model in all_models:
  719. opts = model._meta
  720. # Abstract model's fields are copied to child models, hence we will
  721. # see the fields from the child models.
  722. if opts.abstract:
  723. continue
  724. fields_with_relations = (
  725. f
  726. for f in opts._get_fields(reverse=False, include_parents=False)
  727. if f.is_relation and f.related_model is not None
  728. )
  729. for f in fields_with_relations:
  730. if not isinstance(f.remote_field.model, str):
  731. remote_label = f.remote_field.model._meta.concrete_model._meta.label
  732. related_objects_graph[remote_label].append(f)
  733. for model in all_models:
  734. # Set the relation_tree using the internal __dict__. In this way
  735. # we avoid calling the cached property. In attribute lookup,
  736. # __dict__ takes precedence over a data descriptor (such as
  737. # @cached_property). This means that the _meta._relation_tree is
  738. # only called if related_objects is not in __dict__.
  739. related_objects = related_objects_graph[
  740. model._meta.concrete_model._meta.label
  741. ]
  742. model._meta.__dict__["_relation_tree"] = related_objects
  743. # It seems it is possible that self is not in all_models, so guard
  744. # against that with default for get().
  745. return self.__dict__.get("_relation_tree", EMPTY_RELATION_TREE)
  746. @cached_property
  747. def _relation_tree(self):
  748. return self._populate_directed_relation_graph()
  749. def _expire_cache(self, forward=True, reverse=True):
  750. # This method is usually called by apps.cache_clear(), when the
  751. # registry is finalized, or when a new field is added.
  752. if forward:
  753. for cache_key in self.FORWARD_PROPERTIES:
  754. if cache_key in self.__dict__:
  755. delattr(self, cache_key)
  756. if reverse and not self.abstract:
  757. for cache_key in self.REVERSE_PROPERTIES:
  758. if cache_key in self.__dict__:
  759. delattr(self, cache_key)
  760. self._get_fields_cache = {}
  761. def get_fields(self, include_parents=True, include_hidden=False):
  762. """
  763. Return a list of fields associated to the model. By default, include
  764. forward and reverse fields, fields derived from inheritance, but not
  765. hidden fields. The returned fields can be changed using the parameters:
  766. - include_parents: include fields derived from inheritance
  767. - include_hidden: include fields that have a related_name that
  768. starts with a "+"
  769. """
  770. if include_parents is False:
  771. include_parents = PROXY_PARENTS
  772. return self._get_fields(
  773. include_parents=include_parents, include_hidden=include_hidden
  774. )
  775. def _get_fields(
  776. self,
  777. forward=True,
  778. reverse=True,
  779. include_parents=True,
  780. include_hidden=False,
  781. topmost_call=True,
  782. ):
  783. """
  784. Internal helper function to return fields of the model.
  785. * If forward=True, then fields defined on this model are returned.
  786. * If reverse=True, then relations pointing to this model are returned.
  787. * If include_hidden=True, then fields with is_hidden=True are returned.
  788. * The include_parents argument toggles if fields from parent models
  789. should be included. It has three values: True, False, and
  790. PROXY_PARENTS. When set to PROXY_PARENTS, the call will return all
  791. fields defined for the current model or any of its parents in the
  792. parent chain to the model's concrete model.
  793. """
  794. if include_parents not in (True, False, PROXY_PARENTS):
  795. raise TypeError(
  796. "Invalid argument for include_parents: %s" % (include_parents,)
  797. )
  798. # This helper function is used to allow recursion in ``get_fields()``
  799. # implementation and to provide a fast way for Django's internals to
  800. # access specific subsets of fields.
  801. # Creates a cache key composed of all arguments
  802. cache_key = (forward, reverse, include_parents, include_hidden, topmost_call)
  803. try:
  804. # In order to avoid list manipulation. Always return a shallow copy
  805. # of the results.
  806. return self._get_fields_cache[cache_key]
  807. except KeyError:
  808. pass
  809. fields = []
  810. # Recursively call _get_fields() on each parent, with the same
  811. # options provided in this call.
  812. if include_parents is not False:
  813. # In diamond inheritance it is possible that we see the same model
  814. # from two different routes. In that case, avoid adding fields from
  815. # the same parent again.
  816. parent_fields = set()
  817. for parent in self.parents:
  818. if (
  819. parent._meta.concrete_model != self.concrete_model
  820. and include_parents == PROXY_PARENTS
  821. ):
  822. continue
  823. for obj in parent._meta._get_fields(
  824. forward=forward,
  825. reverse=reverse,
  826. include_parents=include_parents,
  827. include_hidden=include_hidden,
  828. topmost_call=False,
  829. ):
  830. if (
  831. not getattr(obj, "parent_link", False)
  832. or obj.model == self.concrete_model
  833. ) and obj not in parent_fields:
  834. fields.append(obj)
  835. parent_fields.add(obj)
  836. if reverse and not self.proxy:
  837. # Tree is computed once and cached until the app cache is expired.
  838. # It is composed of a list of fields pointing to the current model
  839. # from other models.
  840. all_fields = self._relation_tree
  841. for field in all_fields:
  842. # If hidden fields should be included or the relation is not
  843. # intentionally hidden, add to the fields dict.
  844. if include_hidden or not field.remote_field.hidden:
  845. fields.append(field.remote_field)
  846. if forward:
  847. fields += self.local_fields
  848. fields += self.local_many_to_many
  849. # Private fields are recopied to each child model, and they get a
  850. # different model as field.model in each child. Hence we have to
  851. # add the private fields separately from the topmost call. If we
  852. # did this recursively similar to local_fields, we would get field
  853. # instances with field.model != self.model.
  854. if topmost_call:
  855. fields += self.private_fields
  856. # In order to avoid list manipulation. Always
  857. # return a shallow copy of the results
  858. fields = make_immutable_fields_list("get_fields()", fields)
  859. # Store result into cache for later access
  860. self._get_fields_cache[cache_key] = fields
  861. return fields
  862. @cached_property
  863. def total_unique_constraints(self):
  864. """
  865. Return a list of total unique constraints. Useful for determining set
  866. of fields guaranteed to be unique for all rows.
  867. """
  868. return [
  869. constraint
  870. for constraint in self.constraints
  871. if (
  872. isinstance(constraint, UniqueConstraint)
  873. and constraint.condition is None
  874. and not constraint.contains_expressions
  875. )
  876. ]
  877. @cached_property
  878. def _property_names(self):
  879. """Return a set of the names of the properties defined on the model."""
  880. names = []
  881. for name in dir(self.model):
  882. attr = inspect.getattr_static(self.model, name)
  883. if isinstance(attr, property):
  884. names.append(name)
  885. return frozenset(names)
  886. @cached_property
  887. def _non_pk_concrete_field_names(self):
  888. """
  889. Return a set of the non-pk concrete field names defined on the model.
  890. """
  891. names = []
  892. for field in self.concrete_fields:
  893. if not field.primary_key:
  894. names.append(field.name)
  895. if field.name != field.attname:
  896. names.append(field.attname)
  897. return frozenset(names)
  898. @cached_property
  899. def _reverse_one_to_one_field_names(self):
  900. """
  901. Return a set of reverse one to one field names pointing to the current
  902. model.
  903. """
  904. return frozenset(
  905. field.name for field in self.related_objects if field.one_to_one
  906. )
  907. @cached_property
  908. def db_returning_fields(self):
  909. """
  910. Private API intended only to be used by Django itself.
  911. Fields to be returned after a database insert.
  912. """
  913. return [
  914. field
  915. for field in self._get_fields(
  916. forward=True, reverse=False, include_parents=PROXY_PARENTS
  917. )
  918. if getattr(field, "db_returning", False)
  919. ]