meta.txt 9.8 KB

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