meta.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. ===================
  2. Model ``_meta`` API
  3. ===================
  4. .. module:: django.db.models.options
  5. :synopsis: Model meta-class layer
  6. .. class:: Options
  7. The model ``_meta`` API is at the core of the Django ORM. It enables other
  8. parts of the system such as lookups, queries, forms, and the admin to
  9. understand the capabilities of each model. The API is accessible through
  10. the ``_meta`` attribute of each model class, which is an instance of an
  11. ``django.db.models.options.Options`` object.
  12. Methods that it provides can be used to:
  13. * Retrieve all field instances of a model
  14. * Retrieve a single field instance of a model by name
  15. .. versionchanged:: 1.8
  16. The Model ``_meta`` API has always existed as a Django internal, but
  17. wasn't formally documented and supported. As part of the effort to
  18. make this API public, some of the already existing API entry points
  19. have changed slightly. A :ref:`migration guide <migrating-old-meta-api>`
  20. has been provided to assist in converting your code to use the new,
  21. official API.
  22. .. _model-meta-field-api:
  23. Field access API
  24. ================
  25. Retrieving a single field instance of a model by name
  26. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  27. .. method:: Options.get_field(field_name)
  28. Returns the field instance given a name of a field.
  29. ``field_name`` can be the name of a field on the model, a field
  30. on an abstract or inherited model, or a field defined on another
  31. model that points to the model. In the latter case, the ``field_name``
  32. will be the ``related_name`` defined by the user or the name automatically
  33. generated by Django itself.
  34. :attr:`Hidden fields <django.db.models.Field.hidden>` cannot be retrieved
  35. by name.
  36. If a field with the given name is not found a
  37. :class:`~django.core.exceptions.FieldDoesNotExist` exception will be
  38. raised.
  39. .. code-block:: python
  40. >>> from django.contrib.auth.models import User
  41. # A field on the model
  42. >>> User._meta.get_field('username')
  43. <django.db.models.fields.CharField: username>
  44. # A field from another model that has a relation with the current model
  45. >>> User._meta.get_field('logentry')
  46. <ManyToOneRel: admin.logentry>
  47. # A non existent field
  48. >>> User._meta.get_field('does_not_exist')
  49. Traceback (most recent call last):
  50. ...
  51. FieldDoesNotExist: User has no field named 'does_not_exist'
  52. .. deprecated:: 1.8
  53. :meth:`Options.get_field()` previously accepted a ``many_to_many``
  54. parameter which could be set to ``False`` to avoid searching
  55. ``ManyToManyField``\s. The old behavior has been preserved for
  56. backwards compatibility; however, the parameter and this behavior
  57. has been deprecated.
  58. If you wish to filter out ``ManyToManyField``\s, you can inspect the
  59. :attr:`Field.many_to_many <django.db.models.Field.many_to_many>`
  60. attribute after calling ``get_field()``.
  61. Retrieving all field instances of a model
  62. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  63. .. method:: Options.get_fields(include_parents=True, include_hidden=False)
  64. .. versionadded:: 1.8
  65. Returns a tuple of fields associated with a model. ``get_fields()`` accepts
  66. two parameters that can be used to control which fields are returned:
  67. ``include_parents``
  68. ``True`` by default. Recursively includes fields defined on parent
  69. classes. If set to ``False``, ``get_fields()`` will only search for
  70. fields declared directly on the current model. Fields from models that
  71. directly inherit from abstract models or proxy classes are considered
  72. to be local, not on the parent.
  73. ``include_hidden``
  74. ``False`` by default. If set to ``True``, ``get_fields()`` will include
  75. fields that are used to back other field's functionality. This will
  76. also include any fields that have a ``related_name`` (such
  77. as :class:`~django.db.models.ManyToManyField`, or
  78. :class:`~django.db.models.ForeignKey`) that start with a "+".
  79. .. code-block:: python
  80. >>> from django.contrib.auth.models import User
  81. >>> User._meta.get_fields()
  82. (<ManyToOneRel: admin.logentry>,
  83. <django.db.models.fields.AutoField: id>,
  84. <django.db.models.fields.CharField: password>,
  85. <django.db.models.fields.DateTimeField: last_login>,
  86. <django.db.models.fields.BooleanField: is_superuser>,
  87. <django.db.models.fields.CharField: username>,
  88. <django.db.models.fields.CharField: first_name>,
  89. <django.db.models.fields.CharField: last_name>,
  90. <django.db.models.fields.EmailField: email>,
  91. <django.db.models.fields.BooleanField: is_staff>,
  92. <django.db.models.fields.BooleanField: is_active>,
  93. <django.db.models.fields.DateTimeField: date_joined>,
  94. <django.db.models.fields.related.ManyToManyField: groups>,
  95. <django.db.models.fields.related.ManyToManyField: user_permissions>)
  96. # Also include hidden fields.
  97. >>> User._meta.get_fields(include_hidden=True)
  98. (<ManyToOneRel: auth.user_groups>,
  99. <ManyToOneRel: auth.user_user_permissions>,
  100. <ManyToOneRel: admin.logentry>,
  101. <django.db.models.fields.AutoField: id>,
  102. <django.db.models.fields.CharField: password>,
  103. <django.db.models.fields.DateTimeField: last_login>,
  104. <django.db.models.fields.BooleanField: is_superuser>,
  105. <django.db.models.fields.CharField: username>,
  106. <django.db.models.fields.CharField: first_name>,
  107. <django.db.models.fields.CharField: last_name>,
  108. <django.db.models.fields.EmailField: email>,
  109. <django.db.models.fields.BooleanField: is_staff>,
  110. <django.db.models.fields.BooleanField: is_active>,
  111. <django.db.models.fields.DateTimeField: date_joined>,
  112. <django.db.models.fields.related.ManyToManyField: groups>,
  113. <django.db.models.fields.related.ManyToManyField: user_permissions>)
  114. .. _migrating-old-meta-api:
  115. Migrating from the old API
  116. ==========================
  117. As part of the formalization of the ``Model._meta`` API (from the
  118. :class:`django.db.models.options.Options` class), a number of methods and
  119. properties have been deprecated and will be removed in Django 2.0.
  120. These old APIs can be replicated by either:
  121. * invoking :meth:`Options.get_field()
  122. <django.db.models.options.Options.get_field()>`, or;
  123. * invoking :meth:`Options.get_fields()
  124. <django.db.models.options.Options.get_fields()>` to retrieve a list of all
  125. fields, and then filtering this list using the :ref:`field attributes
  126. <model-field-attributes>` that describe (or retrieve, in the case of
  127. ``_with_model`` variants) the properties of the desired fields.
  128. Although it's possible to make strictly equivalent replacements of the old
  129. methods, that might not be the best approach. Taking the time to refactor any
  130. field loops to make better use of the new API - and possibly include fields
  131. that were previously excluded - will almost certainly result in better code.
  132. Assuming you have a model named ``MyModel``, the following substitutions
  133. can be made to convert your code to the new API:
  134. * ``MyModel._meta.get_field(name)``::
  135. f = MyModel._meta.get_field(name)
  136. then check if:
  137. - ``f.auto_created == False``, because the new ``get_field()``
  138. API will find "reverse" relations), and:
  139. - ``f.is_relation and f.related_model is None``, because the new
  140. ``get_field()`` API will find
  141. :class:`~django.contrib.contenttypes.fields.GenericForeignKey` relations;
  142. * ``MyModel._meta.get_field_by_name(name)``:
  143. ``get_field_by_name()`` returned four values:
  144. ``(field, model, direct, m2m)``:
  145. - ``field`` can be found by ``MyModel._meta.get_field(name)``
  146. - ``model`` can be found through the
  147. :attr:`~django.db.models.Field.model` attribute on the field.
  148. - ``direct`` can be found by: ``not field.auto_created or field.concrete``
  149. The :attr:`~django.db.models.Field.auto_created` check excludes
  150. all "forward" and "reverse" relations that are created by Django, but
  151. this also includes ``AutoField`` and ``OneToOneField`` on proxy models.
  152. We avoid filtering out these attributes using the
  153. :attr:`concrete <django.db.models.Field.concrete>` attribute.
  154. - ``m2m`` can be found through the
  155. :attr:`~django.db.models.Field.many_to_many` attribute on the field.
  156. * ``MyModel._meta.get_fields_with_model()``::
  157. [
  158. (f, f.model if f.model != MyModel else None)
  159. for f in MyModel._meta.get_fields()
  160. if not f.is_relation
  161. or f.one_to_one
  162. or (f.many_to_one and f.related_model)
  163. ]
  164. * ``MyModel._meta.get_concrete_fields_with_model()``::
  165. [
  166. (f, f.model if f.model != MyModel else None)
  167. for f in MyModel._meta.get_fields()
  168. if f.concrete and (
  169. not f.is_relation
  170. or f.one_to_one
  171. or (f.many_to_one and f.related_model)
  172. )
  173. ]
  174. * ``MyModel._meta.get_m2m_with_model()``::
  175. [
  176. (f, f.model if f.model != MyModel else None)
  177. for f in MyModel._meta.get_fields()
  178. if f.many_to_many and not f.auto_created
  179. ]
  180. * ``MyModel._meta.get_all_related_objects()``::
  181. [
  182. f for f in MyModel._meta.get_fields()
  183. if (f.one_to_many or f.one_to_one) and f.auto_created
  184. ]
  185. * ``MyModel._meta.get_all_related_objects_with_model()``::
  186. [
  187. (f, f.model if f.model != MyModel else None)
  188. for f in MyModel._meta.get_fields()
  189. if (f.one_to_many or f.one_to_one) and f.auto_created
  190. ]
  191. * ``MyModel._meta.get_all_related_many_to_many_objects()``::
  192. [
  193. f for f in MyModel._meta.get_fields(include_hidden=True)
  194. if f.many_to_many and f.auto_created
  195. ]
  196. * ``MyModel._meta.get_all_related_m2m_objects_with_model()``::
  197. [
  198. (f, f.model if f.model != MyModel else None)
  199. for f in MyModel._meta.get_fields(include_hidden=True)
  200. if f.many_to_many and f.auto_created
  201. ]
  202. * ``MyModel._meta.get_all_field_names()``::
  203. from itertools import chain
  204. list(set(chain.from_iterable(
  205. (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
  206. for field in MyModel._meta.get_fields()
  207. # For complete backwards compatibility, you may want to exclude
  208. # GenericForeignKey from the results.
  209. if not (field.many_to_one and field.related_model is None)
  210. )))
  211. This provides a 100% backwards compatible replacement, ensuring that both
  212. field names and attribute names ``ForeignKey``\s are included, but fields
  213. associated with ``GenericForeignKey``\s are not. A simpler version would be::
  214. [f.name for f in MyModel._meta.get_fields()]
  215. While this isn't 100% backwards compatible, it may be sufficient in many
  216. situations.