fields.txt 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. PostgreSQL specific model fields
  2. ================================
  3. All of these fields are available from the ``django.contrib.postgres.fields``
  4. module.
  5. .. currentmodule:: django.contrib.postgres.fields
  6. ArrayField
  7. ----------
  8. .. class:: ArrayField(base_field, size=None, **options)
  9. A field for storing lists of data. Most field types can be used, you simply
  10. pass another field instance as the :attr:`base_field
  11. <ArrayField.base_field>`. You may also specify a :attr:`size
  12. <ArrayField.size>`. ``ArrayField`` can be nested to store multi-dimensional
  13. arrays.
  14. .. attribute:: base_field
  15. This is a required argument.
  16. Specifies the underlying data type and behaviour for the array. It
  17. should be an instance of a subclass of
  18. :class:`~django.db.models.Field`. For example, it could be an
  19. :class:`~django.db.models.IntegerField` or a
  20. :class:`~django.db.models.CharField`. Most field types are permitted,
  21. with the exception of those handling relational data
  22. (:class:`~django.db.models.ForeignKey`,
  23. :class:`~django.db.models.OneToOneField` and
  24. :class:`~django.db.models.ManyToManyField`).
  25. It is possible to nest array fields - you can specify an instance of
  26. ``ArrayField`` as the ``base_field``. For example::
  27. from django.db import models
  28. from django.contrib.postgres.fields import ArrayField
  29. class ChessBoard(models.Model):
  30. board = ArrayField(
  31. ArrayField(
  32. CharField(max_length=10, blank=True, null=True),
  33. size=8),
  34. size=8)
  35. Transformation of values between the database and the model, validation
  36. of data and configuration, and serialization are all delegated to the
  37. underlying base field.
  38. .. attribute:: size
  39. This is an optional argument.
  40. If passed, the array will have a maximum size as specified. This will
  41. be passed to the database, although PostgreSQL at present does not
  42. enforce the restriction.
  43. .. note::
  44. When nesting ``ArrayField``, whether you use the `size` parameter or not,
  45. PostgreSQL requires that the arrays are rectangular::
  46. from django.db import models
  47. from django.contrib.postgres.fields import ArrayField
  48. class Board(models.Model):
  49. pieces = ArrayField(ArrayField(models.IntegerField()))
  50. # Valid
  51. Board(pieces=[
  52. [2, 3],
  53. [2, 1],
  54. ])
  55. # Not valid
  56. Board(pieces=[
  57. [2, 3],
  58. [2],
  59. ])
  60. If irregular shapes are required, then the underlying field should be made
  61. nullable and the values padded with ``None``.
  62. Querying ArrayField
  63. ^^^^^^^^^^^^^^^^^^^
  64. There are a number of custom lookups and transforms for :class:`ArrayField`.
  65. We will use the following example model::
  66. from django.db import models
  67. from django.contrib.postgres.fields import ArrayField
  68. class Post(models.Model):
  69. name = models.CharField(max_length=200)
  70. tags = ArrayField(models.CharField(max_length=200), blank=True)
  71. def __str__(self): # __unicode__ on python 2
  72. return self.name
  73. .. fieldlookup:: arrayfield.contains
  74. contains
  75. ~~~~~~~~
  76. The :lookup:`contains` lookup is overridden on :class:`ArrayField`. The
  77. returned objects will be those where the values passed are a subset of the
  78. data. It uses the SQL operator ``@>``. For example::
  79. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  80. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  81. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  82. >>> Post.objects.filter(tags__contains=['thoughts'])
  83. [<Post: First post>, <Post: Second post>]
  84. >>> Post.objects.filter(tags__contains=['django'])
  85. [<Post: First post>, <Post: Third post>]
  86. >>> Post.objects.filter(tags__contains=['django', 'thoughts'])
  87. [<Post: First post>]
  88. .. fieldlookup:: arrayfield.contained_by
  89. contained_by
  90. ~~~~~~~~~~~~
  91. This is the inverse of the :lookup:`contains <arrayfield.contains>` lookup -
  92. the objects returned will be those where the data is a subset of the values
  93. passed. It uses the SQL operator ``<@``. For example::
  94. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  95. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  96. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  97. >>> Post.objects.filter(tags__contained_by=['thoughts', 'django'])
  98. [<Post: First post>]
  99. >>> Post.objects.filter(tags__contained_by=['thoughts', 'django', 'tutorial'])
  100. [<Post: First post>, <Post: Second post>, <Post: Third post>]
  101. .. fieldlookup:: arrayfield.overlap
  102. overlap
  103. ~~~~~~~
  104. Returns objects where the data shares any results with the values passed. Uses
  105. the SQL operator ``&&``. For example::
  106. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  107. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  108. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  109. >>> Post.objects.filter(tags__overlap=['thoughts'])
  110. [<Post: First post>, <Post: Second post>]
  111. >>> Post.objects.filter(tags__overlap=['thoughts', 'tutorial'])
  112. [<Post: First post>, <Post: Second post>, <Post: Third post>]
  113. .. fieldlookup:: arrayfield.index
  114. Index transforms
  115. ~~~~~~~~~~~~~~~~
  116. This class of transforms allows you to index into the array in queries. Any
  117. non-negative integer can be used. There are no errors if it exceeds the
  118. :attr:`size <ArrayField.size>` of the array. The lookups available after the
  119. transform are those from the :attr:`base_field <ArrayField.base_field>`. For
  120. example::
  121. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  122. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  123. >>> Post.objects.filter(tags__0='thoughts')
  124. [<Post: First post>, <Post: Second post>]
  125. >>> Post.objects.filter(tags__1__iexact='Django')
  126. [<Post: First post>]
  127. >>> Post.objects.filter(tags__276='javascript')
  128. []
  129. .. note::
  130. PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
  131. However these indexes and those used in :lookup:`slices <arrayfield.slice>`
  132. use 0-based indexing to be consistent with Python.
  133. .. fieldlookup:: arrayfield.slice
  134. Slice transforms
  135. ~~~~~~~~~~~~~~~~
  136. This class of transforms allow you to take a slice of the array. Any two
  137. non-negative integers can be used, separated by a single underscore. The
  138. lookups available after the transform do not change. For example::
  139. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  140. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  141. >>> Post.objects.create(name='Third post', tags=['django', 'python', 'thoughts'])
  142. >>> Post.objects.filter(tags__0_1=['thoughts'])
  143. [<Post: First post>]
  144. >>> Post.objects.filter(tags__0_2__contains='thoughts')
  145. [<Post: First post>, <Post: Second post>]
  146. .. note::
  147. PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
  148. However these slices and those used in :lookup:`indexes <arrayfield.index>`
  149. use 0-based indexing to be consistent with Python.
  150. .. admonition:: Multidimensional arrays with indexes and slices
  151. PostgreSQL has some rather esoteric behaviour when using indexes and slices
  152. on multidimensional arrays. It will always work to use indexes to reach
  153. down to the final underlying data, but most other slices behave strangely
  154. at the database level and cannot be supported in a logical, consistent
  155. fashion by Django.
  156. Indexing ArrayField
  157. ^^^^^^^^^^^^^^^^^^^
  158. At present using :attr:`~django.db.models.Field.db_index` will create a
  159. ``btree`` index. This does not offer particularly significant help to querying.
  160. A more useful index is a ``GIN`` index, which you should create using a
  161. :class:`~django.db.migrations.operations.RunSQL` operation.