options.py 35 KB

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