options.py 30 KB

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