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.

options.py 34KB

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