meta.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. Retrieving all field instances of a model
  53. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  54. .. method:: Options.get_fields(include_parents=True, include_hidden=False)
  55. .. versionadded:: 1.8
  56. Returns a tuple of fields associated with a model. ``get_fields()`` accepts
  57. two parameters that can be used to control which fields are returned:
  58. ``include_parents``
  59. ``True`` by default. Recursively includes fields defined on parent
  60. classes. If set to ``False``, ``get_fields()`` will only search for
  61. fields declared directly on the current model. Fields from models that
  62. directly inherit from abstract models or proxy classes are considered
  63. to be local, not on the parent.
  64. ``include_hidden``
  65. ``False`` by default. If set to ``True``, ``get_fields()`` will include
  66. fields that are used to back other field's functionality. This will
  67. also include any fields that have a ``related_name`` (such
  68. as :class:`~django.db.models.ManyToManyField`, or
  69. :class:`~django.db.models.ForeignKey`) that start with a "+".
  70. .. code-block:: python
  71. >>> from django.contrib.auth.models import User
  72. >>> User._meta.get_fields()
  73. (<ManyToOneRel: admin.logentry>,
  74. <django.db.models.fields.AutoField: id>,
  75. <django.db.models.fields.CharField: password>,
  76. <django.db.models.fields.DateTimeField: last_login>,
  77. <django.db.models.fields.BooleanField: is_superuser>,
  78. <django.db.models.fields.CharField: username>,
  79. <django.db.models.fields.CharField: first_name>,
  80. <django.db.models.fields.CharField: last_name>,
  81. <django.db.models.fields.EmailField: email>,
  82. <django.db.models.fields.BooleanField: is_staff>,
  83. <django.db.models.fields.BooleanField: is_active>,
  84. <django.db.models.fields.DateTimeField: date_joined>,
  85. <django.db.models.fields.related.ManyToManyField: groups>,
  86. <django.db.models.fields.related.ManyToManyField: user_permissions>)
  87. # Also include hidden fields.
  88. >>> User._meta.get_fields(include_hidden=True)
  89. (<ManyToOneRel: auth.user_groups>,
  90. <ManyToOneRel: auth.user_user_permissions>,
  91. <ManyToOneRel: admin.logentry>,
  92. <django.db.models.fields.AutoField: id>,
  93. <django.db.models.fields.CharField: password>,
  94. <django.db.models.fields.DateTimeField: last_login>,
  95. <django.db.models.fields.BooleanField: is_superuser>,
  96. <django.db.models.fields.CharField: username>,
  97. <django.db.models.fields.CharField: first_name>,
  98. <django.db.models.fields.CharField: last_name>,
  99. <django.db.models.fields.EmailField: email>,
  100. <django.db.models.fields.BooleanField: is_staff>,
  101. <django.db.models.fields.BooleanField: is_active>,
  102. <django.db.models.fields.DateTimeField: date_joined>,
  103. <django.db.models.fields.related.ManyToManyField: groups>,
  104. <django.db.models.fields.related.ManyToManyField: user_permissions>)
  105. .. _migrating-old-meta-api:
  106. Migrating from the old API
  107. ==========================
  108. As part of the formalization of the ``Model._meta`` API (from the
  109. :class:`django.db.models.options.Options` class), a number of methods and
  110. properties have been deprecated and will be removed in Django 1.10.
  111. These old APIs can be replicated by either:
  112. * invoking :meth:`Options.get_field()
  113. <django.db.models.options.Options.get_field()>`, or;
  114. * invoking :meth:`Options.get_fields()
  115. <django.db.models.options.Options.get_fields()>` to retrieve a list of all
  116. fields, and then filtering this list using the :ref:`field attributes
  117. <model-field-attributes>` that describe (or retrieve, in the case of
  118. ``_with_model`` variants) the properties of the desired fields.
  119. Although it's possible to make strictly equivalent replacements of the old
  120. methods, that might not be the best approach. Taking the time to refactor any
  121. field loops to make better use of the new API - and possibly include fields
  122. that were previously excluded - will almost certainly result in better code.
  123. Assuming you have a model named ``MyModel``, the following substitutions
  124. can be made to convert your code to the new API:
  125. * ``MyModel._meta.get_field(name)``::
  126. f = MyModel._meta.get_field(name)
  127. then check if:
  128. - ``f.auto_created == False``, because the new ``get_field()``
  129. API will find "reverse" relations), and:
  130. - ``f.is_relation and f.related_model is None``, because the new
  131. ``get_field()`` API will find
  132. :class:`~django.contrib.contenttypes.fields.GenericForeignKey` relations;
  133. * ``MyModel._meta.get_field_by_name(name)``:
  134. ``get_field_by_name()`` returned four values:
  135. ``(field, model, direct, m2m)``:
  136. - ``field`` can be found by ``MyModel._meta.get_field(name)``
  137. - ``model`` can be found through the
  138. :attr:`~django.db.models.Field.model` attribute on the field.
  139. - ``direct`` can be found by: ``not field.auto_created or field.concrete``
  140. The :attr:`~django.db.models.Field.auto_created` check excludes
  141. all "forward" and "reverse" relations that are created by Django, but
  142. this also includes ``AutoField`` and ``OneToOneField`` on proxy models.
  143. We avoid filtering out these attributes using the
  144. :attr:`concrete <django.db.models.Field.concrete>` attribute.
  145. - ``m2m`` can be found through the
  146. :attr:`~django.db.models.Field.many_to_many` attribute on the field.
  147. * ``MyModel._meta.get_fields_with_model()``::
  148. [
  149. (f, f.model if f.model != MyModel else None)
  150. for f in MyModel._meta.get_fields()
  151. if not f.is_relation
  152. or f.one_to_one
  153. or (f.many_to_one and f.related_model)
  154. ]
  155. * ``MyModel._meta.get_concrete_fields_with_model()``::
  156. [
  157. (f, f.model if f.model != MyModel else None)
  158. for f in MyModel._meta.get_fields()
  159. if f.concrete and (
  160. not f.is_relation
  161. or f.one_to_one
  162. or (f.many_to_one and f.related_model)
  163. )
  164. ]
  165. * ``MyModel._meta.get_m2m_with_model()``::
  166. [
  167. (f, f.model if f.model != MyModel else None)
  168. for f in MyModel._meta.get_fields()
  169. if f.many_to_many and not f.auto_created
  170. ]
  171. * ``MyModel._meta.get_all_related_objects()``::
  172. [
  173. f for f in MyModel._meta.get_fields()
  174. if (f.one_to_many or f.one_to_one) and f.auto_created
  175. ]
  176. * ``MyModel._meta.get_all_related_objects_with_model()``::
  177. [
  178. (f, f.model if f.model != MyModel else None)
  179. for f in MyModel._meta.get_fields()
  180. if (f.one_to_many or f.one_to_one) and f.auto_created
  181. ]
  182. * ``MyModel._meta.get_all_related_many_to_many_objects()``::
  183. [
  184. f for f in MyModel._meta.get_fields(include_hidden=True)
  185. if f.many_to_many and f.auto_created
  186. ]
  187. * ``MyModel._meta.get_all_related_m2m_objects_with_model()``::
  188. [
  189. (f, f.model if f.model != MyModel else None)
  190. for f in MyModel._meta.get_fields(include_hidden=True)
  191. if f.many_to_many and f.auto_created
  192. ]
  193. * ``MyModel._meta.get_all_field_names()``::
  194. from itertools import chain
  195. list(set(chain.from_iterable(
  196. (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
  197. for field in MyModel._meta.get_fields()
  198. # For complete backwards compatibility, you may want to exclude
  199. # GenericForeignKey from the results.
  200. if not (field.many_to_one and field.related_model is None)
  201. )))
  202. This provides a 100% backwards compatible replacement, ensuring that both
  203. field names and attribute names ``ForeignKey``\s are included, but fields
  204. associated with ``GenericForeignKey``\s are not. A simpler version would be::
  205. [f.name for f in MyModel._meta.get_fields()]
  206. While this isn't 100% backwards compatible, it may be sufficient in many
  207. situations.